首页 > JS Promise不理解的地方

JS Promise不理解的地方

在使用Js的Promise时不明白为啥后续的then方法还会被执行,因为上层的then中已经调用reject了。

需要说明的是我测试时使用的是浏览原生Promise对象。

new Promise(function (resolve, reject) {
    console.log('--- a ---');
    new Promise(function (res, rej) {
        console.log('--- b ---')
        res(2)
    })
    .then(function () {
        reject(1);
        console.log('b');
    })
    .then(function () {
        console.log('b2 success');
    }, function () {
        console.log('b2 error');
    });
}).then(function () {
    console.log('a success');
}, function () {
    console.log('a error');
});

// 输出结果
// --- a ---
// --- b ---
// b
// a error
// b2 success

问题:

  1. 为啥先输出b,再输出a error

  2. 为啥b2 success还是会输出?


这个片段里面,reject是一个异步的,console 是一个同步的,等该函数执行完毕后,reject 对应的外层 then 的回掉函数才被执行。

function () {
    reject(1);
    console.log('b');
}

b2 success是因为reject()是外层的
想出现 a error, 必须执行 rej()才有效


如果有兴趣的话,可以读读A+Promise

第一个问题的关键在:

this.done = function (onFulfilled, onRejected) {
    // ensure we are always asynchronous
    setTimeout(function () {
      handle({
        onFulfilled: onFulfilled,
        onRejected: onRejected
      });
    }, 0);
}

至于为什么,可以去了解下event-loop

第二个问题的关键在于,你是做了两个Promise的嵌套,你的reject只是退出了外层Promise,可内层的Promise和外层的(按照你的写法),显然是分别独立的,于是就理所当然的会继续输出自己的b2 success

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