首页 > es6中Promise在执行到resolve的时候会打断当前运行的函数么?

es6中Promise在执行到resolve的时候会打断当前运行的函数么?

例如:

var promise = new Promise(function(resolve, reject){
    setTimeout(function(){
        resolve(1);
        console.log(2);
    }, 1000);
    console.log(3);
});
promise.then(function(data){
    console.log(data);
});

我觉得应该结果是

3
1
2

可是结果却是

3
2
1

请问这是为什么?我觉得当promise执行到reject的时候,会自动跳转到then的函数中去,难道es6中的Promise不会打断函数的执行?


根据规范
调用resolve的时候并没有执行thenAction,而是在第12行调用 EnqueueJob将任务加入执行队列中。


打断的,你可以用这个以下这个,就自动会到catch啦

throw "打断文字提示";

https://promisesaplus.com/#point-34

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

https://promisesaplus.com/#point-67

Here “platform code” means engine, environment, and promise implementation code. In practice, this requirement ensures that onFulfilled and onRejected execute asynchronously, after the event loop turn in which then is called, and with a fresh stack. This can be implemented with either a “macro-task” mechanism such as setTimeout or setImmediate, or with a “micro-task” mechanism such as MutationObserver or process.nextTick. Since the promise implementation is considered platform code, it may itself contain a task-scheduling queue or “trampoline” in which the handlers are called.

这里

resolve(1);
console.log(2);

类似

setTimeout(function (data) {
   console.log(data);
}, 0);
console.log(2);

resolve 的调用是一个类似异步的过程


调用resolve或reject实际上是改变当前Promise实例的状态(pending->fulfilled,或pending-rejected),并附带传给Promise实例一个state值而已,并不是要执行其他处理。
而我们通过then来订阅Promise实例的状态变化,而这个状态变化的事件通知有3个特点:
1. 异步触发:就是状态变化后不会马上执行事件响应函数,而是等待当前任务队列为空时才执行;
2. 仅触发一次:由于Promise实例的状态变化是单向不可逆,因此同一个事件响应函数仅能被执行一次;
3. 延迟绑定:虽然我们订阅的是状态变化事件,但即使实例的状态已经为fulfilled或rejected,我们才订阅事件,依然可以得到触发。

【热门文章】
【热门文章】