promise中调用reject,后面的then方法还会执行?

多个异步操作,如果中间出现reject后面应该不会再执行,
为什么下面代码中第二个then函数还会执行?

function getJson(idx){
    return new Promise(function(resolve,reject){
        setTimeout(function(){
            var random = Math.floor(Math.random() * 1000);
            console.log('success'+random); 
            reject(random);
        },1000)
    })
}


getJson(13).then(function(){
     return getJson(14);
},function(){
    console.log(arguments)
    return "adas";
}).then(function(){
    return  getJson(15);
}).then(function(){
    return  getJson(16);
})
阅读 12.8k
2 个回答

then 返回一个由输入函数确定的Promise:

如果 onFulfilled 或者 onRejected 抛出一个错误,或者返回一个拒绝的 Promise ,then 返回一个 >rejected Promise。
如果 onFulfilled 或者 onRejected 返回一个 resolves Promise,或者返回任何其他值,then 返回一个 >resolved Promise。

https://developer.mozilla.org...返回值

第一个then执行onRejected,返回一个resolved Promise,第二个then执行,但是第二个then没有onRejected,所以简单地采用 Promise 的拒绝状态

楼上从MDN上给了官方的解释,也是正解。但没有给出为什么要这么设计。我就讲一讲这一点。

核心的原因是无法保证同步或异步的唯一性。要理解这一句话,先看这段代码:

let cached = {};

function getJson(idx) {
    return new Promise(function (resolve, reject) {
        if (cached[idx]) {
            console.log('success' + cached[idx]);
            return resolve(cached[idx]);
        }
        setTimeout(function () {
            var random = Math.floor(Math.random() * 1000);
            cached[idx] = random;
            console.log('success' + random);
            resolve(random);
        }, 1000)
    })
}
console.log('start');
getJson(13);
console.log('end');

当未被缓存的情况下返回的是:

start
end
success556

当有缓存的情况下返回的是:

start
success556
end

问题根源是当有缓存的时候,是以同步的形式执行。

所以对于 getJson 无法保证都是异步或同步的情况下,那么 Promise 在设计时就干脆所有的都以异步来解决这一问题。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题