问题
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