两段逻辑相同的Promise代码为何执行结果不一致?
问题:两段Promise代码执行结果不一致的原因分析
我编写了两段逻辑相似的Promise相关代码,但执行结果却不一致,原本期望通过setTimeout让Promise在2秒后resolve,但实际得到了不同的输出结果。
代码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")})});
原因分析
核心差异在于resolve的执行时机和方式:
代码1的错误逻辑:
你直接将setTimeout(work, time)的返回值(定时器ID)传给resolve,这会导致Promise在调用setTimeout的瞬间就完成resolve,完全不会等待time时长。setTimeout只是单独延迟执行work函数,所以then中的第二个order会立刻启动,两个日志的输出顺序会混乱,完全不符合你“2秒后resolve再执行后续逻辑”的预期。代码2的正确逻辑:
你把resolve(work())放在了setTimeout的回调函数内部,这才是正确的延迟resolve方式:等待time时间后,先执行work函数,再触发Promise的resolve。这样第一个order的Promise会在2秒后才完成,then里的第二个order才会在这之后执行,实现了你想要的顺序执行效果。
另外代码中的0o0是八进制表示的0,和十进制的0功能一致,不影响核心逻辑差异。
内容的提问来源于stack exchange,提问作者Avinash Galanki
相关产品推荐
相关产品推荐

