javascript - Use setTimeout to resolve or reject a promise - Stack Overflow

admin2025-04-20  0

I have a code section /

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.

I have a code section https://jsfiddle/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.

Share Improve this question asked Dec 1, 2016 at 4:44 VietNgVietNg 811 silver badge7 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

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.

()=>reject('error') and reject('error') are pletely 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.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745080862a283849.html

最新回复(0)