如果在此之前完成承诺,会发生什么? [英] What happens if a promise completes before then is called?
本文介绍了如果在此之前完成承诺,会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个承诺
,就像这样:
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
<$ c,会发生什么? $ c> 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)
这篇关于如果在此之前完成承诺,会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文