如果在此之前完成承诺,会发生什么?

问题描述:

假设我有一个承诺,就像这样:

Let's say I have a Promise like this:

var promise = new Promise(function(resolve, reject) {
    // Do some async thing
});
promise.then(function(response) {
    // Then do some other stuff
});

如果 async Promise 在我打电话给 .then()之前完成?通常情况下,我只会在 Promise 函数中执行长时间运行的任务,但如果它很快完成一次会怎样?

What happens if the async Promise completes before I call .then()? Normally, I'd only have long running tasks in the Promise function, but what if it completes really quickly one time?

正如预期的那样:如果在promise已经解决后调用,则会立即调用回调函数。

As expected: then callback will get called immediately in this case if then was called after promise has already resolved.

这很容易测试:

var promise = new Promise(function(resolve, reject) {
    resolve(123);
});

setTimeout(function() {
  promise.then(function(response) {
      alert(response);
  });
}, 1000)