Please have a look at this jiddle that replicates the problem. The problem is in Scenario #3:
function processMultistagePromiseBad(func1data, func2data) {
console.log("func1data:", func1data);
console.log("func2data:", func2data);
return work1(func1data)
.then(work2(func2data));
}
// scenario 3
processMultistagePromiseBad(data1, data2)
.then((results) => {
console.log(results);
return results;
})
.then((results) => scenario3.innerHTML += results + " <br />");
For both scenario 3 & 4, I'm passing 2 data objects to a js function, that is calling work1 & work2 functions in a promise chain. Work2 is running in both scenarios but scenario 3 isn't returning correctly....why??
Scenario 4, adding the function declaration is working as expected...?
Thanks, Tim
.then expects handler functions that will return a value helping to resolve/ exception that will reject the promise - what you are passing here is a promise to the .then and it simply gets ignored. Return the result to resolve the first promise
Refer - chaining promises
function processMultistagePromiseBad(func1data, func2data) { console.log("func1data:", func1data); console.log("func2data:", func2data); return work1(func1data) .then((result) => { return work2(func2data); }); }
EDIT:
Then itself returns a promise. The return value of your resolve/ reject function is passed on to the new promise. The next then in your chain uses this value as input. In processMultistagePromiseBad, work1(func1data) returns a promise with resolve value of "I am data 1". then(work2(func2data)) does not return a new promise with return value "I am data 2" because it is not resturning anything. Therefore processMultistagePromiseBad returns the first promise - "I am data 1" since it was not reassigned by the next then. Whereas in processMultistagePromiseGood it gets reassigned. Promises are really confusing but it comes in handy when we want to execute something async. Hope this helps - MSDN documentation on then
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.