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.
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 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.