我有两个与 Promise 相关的代码..逻辑是相同的...但产生不同的输出,为什么?
代码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`)})})
代码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")})});
我尝试创建一个承诺,我的目标是通过使用 setTimeout 属性在 2 秒后重新恋爱……但得到不同的输出
代码1中的这个结构:
resolve(setTimeout(work,time));
立即解析promise,解析后的值是
setTimeout()
的返回值,即timerID。 计时器尚未触发,因为 setTimeout()
是非阻塞的(立即返回,计时器稍后触发)。
代码2中的这个结构:
setTimeout(()=>{resolve(work())},time);
仅在计时器触发时(不是立即)解析承诺,并且解析的值是调用
work()
函数的返回值。