首页 > web前端 > js教程 > 正文

如何使用 Promise.all 从 URL 数组中获取和解析文本数据?

Susan Sarandon
发布: 2024-10-26 16:16:30
原创
719 人浏览过

How to Fetch and Parse Text Data from an Array of URLs with Promise.all?

使用 Promise.all 获取 URL 数组

利用 Promise.all 从一组 URL 中检索文本数据数组是一种合适的方法。以下是有效完成此任务的方法:

假设您有一个 URL 字符串数组:

<code class="js">var urls = ['1.txt', '2.txt', '3.txt']; // Text files containing "one", "two", "three"</code>
登录后复制

所需的输出是一个文本内容数组:

<code class="js">var text = ['one', 'two', 'three'];</code>
登录后复制

使用 Promise.all 允许您链接多个异步操作。在这种情况下,它可用于首先获取每个 URL,然后从每个响应中提取文本:

<code class="js">Promise.all(urls.map(url => fetch(url)))
  .then(responses =>
    Promise.all(responses.map(res => res.text()))
  )
  .then(texts => {
    // ...
  });</code>
登录后复制

在上面的代码中,Promise.all 使用了两次:一次用于启动所有响应的获取URL,并再次从每个响应中获取文本内容。

另一种方法,将这两个操作组合到一个 Promise.all 链中,可以实现如下:

<code class="js">Promise.all(urls.map(url =>
  fetch(url)
    .then(resp => resp.text())
))
.then(texts => {
  // ...
});</code>
登录后复制

此外,您可以使用 async/await 进一步简化此代码:

<code class="js">const texts = await Promise.all(urls.map(async url => {
  const resp = await fetch(url);
  return resp.text();
}));</code>
登录后复制

这两种方法都有效地利用 Promise.all 来实现获取 URL 数组并提取关联文本内容的预期结果。

以上是如何使用 Promise.all 从 URL 数组中获取和解析文本数据?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!