VietNg
VietNg

Reputation: 81

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.

Upvotes: 2

Views: 3639

Answers (2)

Lewis
Lewis

Reputation: 14866

()=>reject('error') and reject('error') are completely different. In this case, the first syntax is an equivalent to function(){ reject('error')} while calling reject('error') without wrapping it within a callback will immediately invoke the function.

Upvotes: 2

Kevin Stubbs
Kevin Stubbs

Reputation: 323

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.

Upvotes: 5

Related Questions