Why these two codes are executing differently?

25 Views Asked by At

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

1

There are 1 best solutions below

0
On

This structure in code 1:

 resolve(setTimeout(work,time));

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 as setTimeout() is non-blocking (returns immediately and the timer fires later).

This structure in code 2:

setTimeout(()=>{resolve(work())},time);

resolves the promise only when the timer fires (not immediately) and the resolved value is the return value from calling the work() function.