【发布时间】:2020-09-03 11:17:09
【问题描述】:
在本文的上下文中:Graceful asynchronous programming with Promises。并在部分:“运行代码以响应多个承诺履行”。
对于这个特定的代码 sn-p :
function fetchAndDecode(url, type) {
return fetch(url).then(response => {
if (type === 'blob') {
return response.blob();
} else if (type === 'text') {
return response.text();
}
})
.catch(e => {
console.log('There has been a problem with your fetch operation: ' + e.message);
});
}
let coffee = fetchAndDecode('coffee.jpg', 'blob');
let tea = fetchAndDecode('tea.jpg', 'blob');
let description = fetchAndDecode('description.txt', 'text');
Promise.all([coffee, tea, description]).then(values => {
});
它在文章中说:在块的末尾,我们链接一个 .catch() 调用,以处理可能出现的任何错误情况,这些错误情况可能伴随着数组中传递给 .all() 的任何承诺。 如果任何一个 promise 被拒绝,catch 块会告诉你哪个有问题。 .all() 块(见下文)仍会实现,但不会显示有问题的资源。如果您希望 .all 拒绝,则必须将 .catch() 块链接到那里的末尾。
如果任何 Promise 被拒绝,为什么 .all() 块会执行?看看Promise.all() refrence on MDN,它说 .all() 块只有在所有承诺都实现时才会实现。
另外,如果我们无法从 url 获取并且我们将进入 .catch 块,那么函数返回的 Promise 状态是什么,在这种情况下,Promise 的状态是否仍将处于未决状态??
【问题讨论】:
-
您显示的
.catch()处理拒绝并将其转化为已履行的承诺。因此,您的Promise.all()没有任何被拒绝的承诺。这通常不是您使用Promise.all()编程的方式。如果你想要所有结果,Javascript 有Promise.allSettled()。不管有没有失败。
标签: javascript asynchronous promise