承诺开始得太早 [英] Promise starts too early
问题描述
我有以下承诺:
const promise = new Promise((resolve,reject) => {
setTimeout(()=> { resolve('Hello')},4000);
});
后来,我这样称呼它:
promise.then((msg) => {console.log(msg)});
我希望由于超时,在呼叫然后
后4秒钟会显示'Hello'消息,但实际上会立即显示...
I was expecting that the 'Hello' message is displayed 4 seconds after the call to then
due to the timeout, but it is actually displayed right away...
可以肯定我缺少什么:什么?
It is sure something I'm missing: what?
推荐答案
我这样称呼它
您不会拨打"电话;一个承诺.它不是一个函数(尽管它确实具有方法).根据这个问题,我知道您做了第一部分( const promise = new Promise(/*...*/);
),然后稍后做了第二部分( promise.then(/*...*/);
),并且您希望计时器在您执行 then
时启动,而不是在您执行 new时启动答应
.
You don't "call" a promise. It's not a function (though it does have methods). From the question I understand that you did the first part (const promise = new Promise(/*...*/);
), and then later did the second part (promise.then(/*...*/);
), and you expected the timer to start when you did then
, not when you did new Promise
.
但是Promises的工作方式是,您在执行 new Promise
时启动了计时器,而不是在随后调用 then
时启动了计时器.传递给 new Promise
的函数( promise执行者函数)称为同步和立即.其目的是启动承诺将报告其完成情况的操作.
But the way Promises work, your timer was started when you did new Promise
, not later when you called then
. The function you pass into new Promise
(the promise executor function) is called synchronously and immediately. Its purpose is to start the operation that the promise is going to report the completion of.
这可能有助于使其更加清晰:
This may help make it a bit more clear:
const start = Date.now();
function log(msg) {
const elapsed = String(Date.now() - start).padStart(4, " ");
console.log(`${elapsed}: ${msg}`);
}
log("A");
const promise = new Promise((resolve, reject) => {
log("B: Starting 5000ms timer");
setTimeout(() => {
resolve("Hello");
}, 5000);
log("C");
});
log("D: Waiting 2000ms before calling `then`");
setTimeout(() => {
log("F: Calling `then`");
promise.then((msg) => {
log("G");
log(msg)
});
}, 2000);
log("E");
注意输出是
0: A
1: B: Starting 5000ms timer
2: C
2: D: Waiting 2000ms before calling `then`
2: E
,然后大约两秒钟后:
2002: F: Calling `then`
然后大约三秒钟(从开始起五秒钟)
and then about three seconds later (five seconds since the start)
5002: G
5004: Hello
注意事项:
- promise执行程序立即同步运行,并启动其5秒钟计时器
- 何时致电
然后
都没有关系.我等待呼叫然后
2秒钟,但在总计 5(而不是7)秒 后仍然得到了实现回调
- The promise executor was run synchronously and immediately, and start its 5 second timer
- It doesn't matter when you call
then
. I waited to callthen
for 2 seconds, but still got the fulfillment callback after a total of 5 (not 7) seconds
我在上面描述的是诺言的标准行为.(不幸的是,在我看来)那里有一些类似诺言的事情,它们的行为略有不同, do 在开始之前先等待先调用 then
他们的过程.这些不典型,但遗憾的是它们确实存在.
What I describe above is the standard behavior for promises. There are (unfortunately, in my view) a small number of promise-like things out there that behave slightly differently, that do wait for the first call to then
before they start their process. Those are not typical, but sadly they do exist.
这篇关于承诺开始得太早的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!