使用 Promise.all 获取 URL 数组
利用 Promise.all 从一组 URL 中检索文本数据数组是一种合适的方法。以下是有效完成此任务的方法:
假设您有一个 URL 字符串数组:
var urls = ['1.txt', '2.txt', '3.txt']; // Text files containing "one", "two", "three"
期望输出为文本内容数组:
var text = ['one', 'two', 'three'];
使用 Promise.all 允许您链接多个异步操作。在这种情况下,它可用于首先获取每个 URL,然后从每个响应中提取文本:
Promise.all(urls.map(url => fetch(url)))
.then(responses =>
Promise.all(responses.map(res => res.text()))
)
.then(texts => {
// ...
});
在上面的代码中,Promise.all 使用了两次:一次用于发起所有 URL 的抓取,第二次用于从每个响应中获取文本内容。
An另一种方法是将两个操作组合到一个 Promise.all 链中,可以实现如下:
Promise.all(urls.map(url =>
fetch(url)
.then(resp => resp.text())
))
.then(texts => {
// ...
});
此外,您可以使用 async/await 进一步简化此代码:
const texts = await Promise.all(urls.map(async url => {
const resp = await fetch(url);
return resp.text();
}));
这两种方法都有效地利用 Promise.all 来实现获取 URL 数组并提取关联文本内容的预期结果。
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3