When Promise.then() hooks are called?

£可爱£侵袭症+ 提交于 2019-11-30 19:38:15

问题


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.");

When exactly onFullfilled() is guaranteed to be called on Promise resolution?

* In my case "Completed" log message appears after test framework report assertion failure.


回答1:


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.

Since promises sometimes resolve asynchronously the specification mandates they are always resolved asynchronously so the same code path executes. Promises guard you against Zalgo.

It is specified here:

onFulfilled or onRejected must not be called until the execution context stack contains only platform code.

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
})



回答2:


You should always give a function to "then". So you should use "onFullfilled()" instead of "onFullfilled" as parameter of "then".

So it should be like:

Promise.resolve(true).then(onFullfilled());



来源:https://stackoverflow.com/questions/29454949/when-promise-then-hooks-are-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!