In the code below , Values are RETURNED correctly from a queued Promise.then() chain .
CODE:
let cond_1 = true;
let data = 'Data Received....';
let err = 'Error';
var p1 = new Promise(function(resolve,reject){
if(cond_1){
resolve(data);
}else{
reject(err); }})
p1.then((data)=>{console.log(data);return 'Wait....';})
.then((val1)=>{console.log(val1); return 'Finished';})
.then((val2)=>{console.log(val2)})
.catch((err)=>{console.log(err)});
Output :
Data Received....
Wait....
Finished
However, the same RETURNED values from a chained SetTimeout function are returned 'UNDEFINED'.
CODE:
p1.then((data)=>{console.log(data); return 'Wait.....'; })
.then((val1)=>{setTimeout(function(val1){console.log(val1); return 'Finished';},1000)})
.then((val2)=>{setTimeout(function(val2){console.log(val2);},1000)})
.catch((err)=>{console.log(err)});
Output:
Data Received....
undefined
undefined
How to resolve this?
Try taking advantage of Lexicographic nature of Javascript.
Instead of making a function v1,v2 which your functions takes within setTimeout, just use an arrow function. In this way you are using the v1,v2 returned from promise.
Do this
let cond_1 = true;
let data = 'Data Received....';
let err = 'Error';
var p1 = new Promise(function(resolve, reject) {
if (cond_1) {
resolve(data);
} else {
reject(err);
}
})
p1.then((data) => {
console.log(data);
return 'Wait.....';
})
.then((val1) => {
setTimeout(() => {
console.log(val1);
}, 1000);
return 'Finished';
})
.then((val2) => {
return setTimeout(() => {
console.log(val2)
}, 1000)
})
.catch((err) => {
console.log(err)
});
What you did was you created a new variable v1,v2 for your function. You can only use that when you pass value v1,v2 in that function. That function won't use v1,v2 returned from promise as you expect.