javascript - 使用 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() 格式重写它?
解决方案
好的,这是现在的解决方案。对不起,它的语法很丑,我相信有更好的方法来写这个。
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”语句。谢谢您的帮助
推荐阅读
- c# - 显示触摸键盘代码在计算机上可以正常工作,但在平板电脑上不行?
- python - 对熊猫多索引中每个级别 1 的值进行排序
- laravel - 在 laravel 控制器中发送请求后显示模式
- javascript - 是否有不同的方法可以在本地或在上传的网页上控制字体粗细?
- svn - svn 在“更新”上删除本地编辑文件,而不是引发冲突
- php - 仅从数据库中获取第一个元素
- kubernetes - 如何从 kubernetes pod 中获取 configmap
- python - 从 python 执行事件
- excel - 如何计算散点图中的系列
- java - 如何从本地 Maven 存储库中删除特定库