英文:
Why these two codes are executing differently?
问题
Here's the translated content you requested:
我有两个与 promises 相关的代码...逻辑相同...但为什么产生不同的输出?
代码 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("商店已关闭");
}
})
};
order(2000, () => { console.log("订单已下"); })
.then(() => { order(0o0, () => { console.log(`生产已开始`) }) })
代码 2
// 代码 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("商店已关闭");
}
})
}
order(2000, () => { console.log("订单已下"); })
.then(() => { order(0o0, () => { console.log("生产已开始") }) });
我尝试创建了一个 promise,并使用 setTimeout 属性将 promise 定位为在 2 秒后解析,但得到了不同的输出。
英文:
I am having two codes related to promises..the logic is same...but producing different outputs why?
code 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`)})})
code 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")})});
I have tried creating a promise and i am targeting the promise to reslove after 2secs by using setTimeout property...but getting different outputs
答案1
得分: 2
在代码1中的这个结构:
resolve(setTimeout(work, time));
会立即解决Promise,解决的值是来自setTimeout()
的返回值,即计时器的ID。计时器还没有触发,因为setTimeout()
是非阻塞的(立即返回,计时器稍后触发)。
在代码2中的这个结构:
setTimeout(() => { resolve(work()) }, time);
只有在计时器触发时(不是立即),才会解决Promise,解决的值是调用work()
函数的返回值。
英文:
This structure in code 1:
resolve(setTimeout(work,time));
Resolves the promise immediately and the resolved value is the return value from setTimeout()
which is the timerID. The timer will not yet have fired as setTimeout()
is non-blocking (returns immediately and the timer fires later).
This structure in code 2:
setTimeout(()=>{resolve(work())},time);
resolves the promise only when the timer fires (not immediately) and the resolved value is the return value from calling the work()
function.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论