Reputation: 2311
Consider the following function written using callbacks. It returns a token and executes a method asynchronously.
var token = 1;
function requestSupport(callback) {
setTimeout(() => {
console.log(token + ":How may I help you?");
callback(); //when executive is available
}, 5000);
return ++token; //instantly give the token number
}
The ease of callbacks is that the function was able to return the token number (immediately) and also execute code asynchronously and inform when assistance is available. What should this function look like when trying to rewrite using Promises? PROBLEM: If a function returns a promise, the user won't get the token number as a function can return one thing.
Upvotes: 3
Views: 51
Reputation: 371148
You want to return both the token and the Promise - you can do this with any data structure you want, perhaps an object:
var token = 1;
function requestSupportProm() {
const prom = new Promise((resolve) => {
setTimeout(() => {
console.log(token + ":How may I help you?");
resolve(); //when executive is available
}, 2000);
});
return {
prom,
token: ++token
};
}
(() => {
// later;
const { prom, token } = requestSupportProm();
console.log('Got token:', token);
prom.then(() => {
console.log('Promise resolved');
});
})();
Could also use an array, eg return [prom, ++token]
, but the object with named properties will probably be easier to understand at a glance.
Upvotes: 4