I am having two codes related to promises..the logic is same...but producing different outputs why?
code 1
const is_shop_open = true;
const order = (time,work)=>{
return new Promise((resolve,reject)=>{
if(is_shop_open===true){
resolve(setTimeout(work,time));
}
else{
reject("Shop is closed");
}
})
};
order(2000,()=>{console.log("Order was placed")})
.then(()=>{order(0o0,()=>{console.log(`production has started`)})})
code 2
//code 2
const is_shop_open = true;
const order = (time,work)=>{
return new Promise((resolve,reject)=>{
if(is_shop_open===true){
setTimeout(()=>{resolve(work())},time);
}else{
reject("Shop is closed");
}
})
}
order(2000,()=>{console.log("Order was placed")})
.then(()=>{order(0o0,()=>{console.log("Production has started")})});
I have tried creating a promise and i am targeting the promise to reslove after 2secs by using setTimeout property...but getting different outputs
This structure in code 1:
Resolves the promise immediately and the resolved value is the return value from
setTimeout()
which is the timerID. The timer will not yet have fired assetTimeout()
is non-blocking (returns immediately and the timer fires later).This structure in code 2:
resolves the promise only when the timer fires (not immediately) and the resolved value is the return value from calling the
work()
function.