VietNg VietNg - 8 days ago 5
Javascript Question

Use setTimeout to resolve or reject a promise

I have a code section https://jsfiddle.net/h3m10005/

let p = new Promise((resolve, reject) =>{
setTimeout(()=>reject('error'), 5000);
});

p.then(null,(err)=>{
console.log(err);
});


When the above code section gets executed, after approximately 5 secs I will see
error
printed. However, if I dont wrap the reject() call in a function, the console outputs
error
immediately. For example,

let p = new Promise((resolve, reject) =>{
setTimeout(reject('error'), 5000);
});

p.then(null,(err)=>{
console.log(err);
});


Any idea why this might be the case? Thanks.

Answer

It's because in your second example you are calling it immediately.

setTimeout(reject('error'), 5000);

Is essentially using the result of calling reject('error') as the first argument for setTimeout.