【问题标题】:Handling 500 and other errors when requesting multiple urls using fetch and promise all使用 fetch 和 promise all 请求多个 url 时处理 500 和其他错误
【发布时间】:2021-11-23 21:27:28
【问题描述】:

我正在尝试使用 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() 格式重写它?

【问题讨论】:

  • 这能回答你的问题吗? How do I handle errors with promises?
  • 说实话 - 不 - 不是很有帮助。
  • 只需在.then() 之后添加.catch(() => {/* code here */});...
  • 这是我尝试的第一件事。我测试了两个 then 语句,以及在 fetch 之后。这些都没有发现错误。
  • 对不起; fetch (MDN) - fetch() 承诺不会拒绝 HTTP 错误(404 等)。相反,then() handler must check the Response.ok` 和/或 Response.status 属性。”

标签: javascript promise fetch


【解决方案1】:

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

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”语句。感谢您的帮助

【讨论】:

  • 您应该检查response.status >= 200 && response.status < 300 或只检查response.ok,而不是检查状态代码。 200-299(含)之间的每个状态码都是成功状态。 IMO,300中的一些也“成功”了。你可以阅读更多关于status codes on MDN的信息。
  • 感谢您的建议。我实际上需要检查 500 错误才能创建要返回的自定义响应对象。
猜你喜欢
  • 2021-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-14
相关资源
最近更新 更多