I've promise chain which the response in the first chain should be used later on in the chain (in 4 & 6) places, I use some global variable to handle it but this is not the right way ,there is a better way to achieve this with promise?
This is some illustration for the issue...
var step1 = (ms) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
log("This is step 1");
resolve(20);
}, ms);
})
}
var step2 = (ms) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
log("This is step 2");
resolve();
}, ms);
})
};
var step3 = (ms) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
log("This is step 3");
resolve();
}, ms);
})
};
var step4 = (ms) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
log("Step 4, run : " + ms );
resolve();
}, ms);
})
};
var globalVar = null;
//Promise chain
step1(500)
.then((res) => {
//Here I keep the response in global variable to use later on
globalVar = res;
log(res);
return step2(300);
}).then(() => {
return step3(200);
}).then(() =>{
//Here I need to use the res from the first promise
var lclvar = globalVar +200 ;
return step4(lclvar);
}).catch((err) => {
log(err);
});
I found this but this is not helping in this case(at least didn't able to handle it)
How do I access previous promise results in a .then() chain?