I have below code consisting of three functions and a call back function. The challenge I am facing here is : I have to print A , then B and then C in this sequence only
I have tried below code but it always prints C , B and then A
I understand that this is happening due to the fact that setTimeout A > setTimeout B > setTimeout C.
But is there any way that I can call B only when A's response is obtained and C is called only when B's response is obtained.
Please help as I am stuck here
const print = (err, contents) => { if (err) console.error(err) else console.log(contents) } const opA = (cb) => { setTimeout(() => { cb(null, 'A') }, 500) } const opB = (cb) => { setTimeout(() => { cb(null, 'B') }, 250) } const opC = (cb) => { setTimeout(() => { cb(null, 'C') }, 125) } Code I tried :
function promisifyA(){ return new Promise( (resolve,reject) => { resolve(opA(print)); }); } function promisifyB(){ return new Promise( (resolve,reject) => { resolve(opB(print)); }); } function promisifyC(){ return new Promise( (resolve,reject) => { resolve(opC(print)); }); } promisifyA().then(() => { return promisifyB(); }).then(() => { return promisifyC(); });
return new Promise( (resolve,reject) => { opA(resolve); });- otherwise you only haveprintas the callback but still callresolveimmediately. Then usepromisifiedA().then(print).then(promisifiedB).then(print).….