何时调用Promise.then()挂钩? [英] When Promise.then() hooks are called?
问题描述
我发现Firefox的承诺中推迟了完整性通知。断言失败,因为onFullfilled()被称为为时太晚 * 。
I observe deferring of completeness notifications in Firefox's promises. Following assertion fails, because onFullfilled() is called too late*.
var resolved = false;
function onFullfilled() {
resolved = true;
log("Completed");
}
Promise.resolve(true).then(onFullfilled);
assert(resolved, "Promise completed promise should call resolution hook immediately.");
何时保证在Promise分辨率上精确调用onFullfilled()?
When exactly onFullfilled() is guaranteed to be called on Promise resolution?
*在我的情况下,测试框架报告声明失败后出现 Completed日志消息。
推荐答案
在所有同步代码执行完毕后,始终称为Prom决议挂钩。
Promise resolution hooks are always called after all sync code is executed. This is by design - and is done in order to prevent race conditions.
由于promise有时异步地解析它们的规范要求,所以总是 被异步地解决。因此执行相同的代码路径。承诺守卫您反对Zalgo 。
Since promises sometimes resolve asynchronously the specification mandates they are always resolved asynchronously so the same code path executes. Promises guard you against Zalgo.
它是在此处指定:
onFulfilled或onRejected必须在执行上下文堆栈仅包含平台代码之前被调用。
onFulfilled or onRejected must not be called until the execution context stack contains only platform code.
很多测试框架-即Mocha支持通过返回承诺直接使用承诺语法测试承诺。
A lot of test frameworks - namely Mocha support testing promises directly with promise-syntax - by returning a promise.
it("does something", function(){
return aPromise; // if aPromise resolves the test passes
})
这篇关于何时调用Promise.then()挂钩?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!