多个异步操作,如果中间出现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);
})
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
https://developer.mozilla.org...返回值
第一个then执行onRejected,返回一个resolved Promise,第二个then执行,但是第二个then没有onRejected,所以简单地采用 Promise 的拒绝状态
楼上从MDN上给了官方的解释,也是正解。但没有给出为什么要这么设计。我就讲一讲这一点。
核心的原因是无法保证同步或异步的唯一性。要理解这一句话,先看这段代码:
当未被缓存的情况下返回的是:
start
end
success556
当有缓存的情况下返回的是:
start
success556
end
问题根源是当有缓存的时候,是以同步的形式执行。
所以对于
getJson无法保证都是异步或同步的情况下,那么Promise在设计时就干脆所有的都以异步来解决这一问题。