首页 > 解决方案 > 使用 fetch 和 promise all 请求多个 url 时处理 500 和其他错误

问题描述

我正在尝试使用 fetch 和 promise all 从网站上抓取新闻文章。在这里找到的例子

这是我正在使用的代码。

        var openArticles = function(urlArray){

              Promise.all(urlArray.map(u=>fetch(u))).then(responses =>
                Promise.all(responses.map(res => res.text()))
                ).then(function(html){
                  console.log(html[0])
                 
              })
         };

我对箭头函数表达式不太熟悉,并且很难为 500 和超时错误添加错误处理。我尝试将代码放在 try catch 块中,但这没有帮助,我不确定在哪里或如何输入 if 语句来检查响应状态。有没有办法使用标准函数 name() 格式重写它?

标签: javascriptpromisefetch

解决方案


好的,这是现在的解决方案。对不起,它的语法很丑,我相信有更好的方法来写这个。

Promise.all(urls.map(u=>fetch(u).then((response) =>{
   if(response.status != 200){
     console.log(response.status);
     // do something
    return;
  }
  else{
   return response;
  }
 }))).then(responses => Promise.all(responses.map(res => res.text())) 
).then(function(html){
 //do something else
})

基本上我一直在错误的位置添加“then”语句。谢谢您的帮助


推荐阅读