Bai*_*man 6 javascript es6-promise
我面临关于Promise.all错误处理的问题
我希望以下代码在getNetworkstuff()Promises之一失败时调用链的catch部分。但是相反,它只调用下一个然后的部分,并且浏览器控制台显示未捕获的错误。
Promise.all(
[[getNetworkstuff(url1)],[getNetworkstuff(url2)]]
//please note that the arrays within the array are larger in my application
//otherwise I would just use one big array not arrays in arrays
)
.then(function(result){//Stuff worked})
.catch(function(err){//Stuff broke});
function getNetworkstuff(url){
return new Promise(function(resolve,reject){//here will be awesome network code})
}
Run Code Online (Sandbox Code Playgroud)
我可以看到诺言没有实现,因为返回的result数组包含适当的拒绝诺言。
[[PromiseStatus]]: "rejected"
[[PromiseValue]]: Error: HTTP GET resulted in HTTP status code 404.
Run Code Online (Sandbox Code Playgroud)
有人可以告诉我为什么catch不打电话吗?(我知道这是我是否只有一堆承诺Promise.all()(其中有人拒绝))
查看你的控制台
function getNetworkstuff(url) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
console.log('resolving', url);
resolve(url);
}, 5000);
});
}
Promise.all([[getNetworkstuff('url1')],[getNetworkstuff('url2')]])
.then(function(result){
console.log('It worked', result);
})
.catch(function(err){
console.log('It failed', result);
});
Run Code Online (Sandbox Code Playgroud)
请注意,在解决任何问题之前 5 秒,它会输出“It Worked”
Promise.all([getNetworkstuff('url1'), getNetworkstuff('url2')])
.then(function(result){
console.log('It worked', result);
})
.catch(function(err){
console.log('It failed', result);
});
Run Code Online (Sandbox Code Playgroud)
现在在没有数组的数组的情况下进行比较 - 请注意It Worked两种情况下旁边记录的内容的差异
最后,运行这个
function getNetworkstuff(url) {
return new Promise(function(resolve, reject) {
if(url == 'url1') {
setTimeout(function() {
console.log('resolving', url);
resolve(url);
}, 5000);
}
else {
console.log('rejecting', url);
reject(url);
}
});
}
Promise.all([getNetworkstuff('url1'), getNetworkstuff('url2')])
.then(function(result){
console.log('It worked', result);
})
.catch(function(err){
console.log('It failed', result);
});
Run Code Online (Sandbox Code Playgroud)
您的后续问题:how are they kicked of if not being recognized as promises
您是否可以看到下面的代码与您对可能返回或不返回承诺的函数结果数组所做的操作类似?无论如何,拿走承诺和然后的东西......你就得到了这个
function fn(s) {
return s.toUpperCase();
}
function fn2(arr) {
console.log(arr); // [["A"], ["B"]]
}
fn2([[fn('a')],[fn('b')]]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
780 次 |
| 最近记录: |