简体   繁体   English

Promise的State和Promise.all()中的查询是什么?

[英]What is State of Promise and query in Promise.all()?

In the context of this article: Graceful asynchronous programming with Promises .在本文的上下文中: 使用 Promises 进行优雅的异步编程 And in section: "Running code in response to multiple promises fulfilling".在部分中:“运行代码以响应多个承诺的实现”。

For this particular Code snippet:对于这个特定的代码片段:

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 => {

});

It says in article: At the end of the block, we chain on a.catch() call, to handle any error cases that may come up with any of the promises passed in the array to.all().它在文章中说:在块的末尾,我们链接 a.catch() 调用,以处理可能出现的任何错误情况,这些错误情况可能与数组中传递给.all() 的任何承诺有关。 If any of the promises reject, the catch block will let you know which one had a problem.如果有任何 promise 被拒绝,catch 块会让您知道哪个 promise 有问题。 The.all() block (see below) will still fulfil, but just won't display the resources that had problems . The.all() 块(见下文)仍将执行,但不会显示有问题的资源 If you wanted the.all to reject, you'd have to chain the.catch() block on to the end of there instead.如果您希望 the.all 被拒绝,则必须将 the.catch() 块链接到那里的末尾。

Why.all() block will fulfil if any Promise gets rejected?如果任何 Promise 被拒绝,为什么 .all() 块将执行? Looking at Promise.all() refrence on MDN it says.all() block will only get fulfill when all the promises will get fulfil.查看MDN上的 Promise.all() 引用,它说。all() 块只有在所有承诺都得到履行时才会得到履行。

Also what will be the state of promise returned by the function, if we are unable to fetch from url and we will enter.catch block, wouldn't the state of promise will still be pending in that case??另外,function 返回的 promise 的 state 是什么,如果我们无法从 url 获取并且我们将 enter.catch 块,promise 的 state 不会吗?在那种情况下仍将悬而未决

Your confusion is understandable.你的困惑是可以理解的。 The piece that you are missing is that the Promise.all will always succeed, because you are adding a catch to each individual promise .您缺少的部分是Promise.all 将始终成功,因为您正在为每个人添加一个 catch promise

So even if one of the sub-promises fails, you'll just get undefined instead of the value, but you've already handled any rejections.因此,即使其中一个子承诺失败,您也只会得到undefined而不是值,但您已经处理了所有拒绝。 Once you .catch the resulting Promise is considered resolved, not rejected.一旦您.catch结果 Promise 被认为已解决,而不是被拒绝。 If you want it to still be rejected, you can re-throw the error after logging.如果你希望它仍然被拒绝,你可以在记录后重新抛出错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM