如何使用 Promise.all 获取 URL 数组? [英] How can I fetch an array of URLs with Promise.all?

查看:19
本文介绍了如何使用 Promise.all 获取 URL 数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一组网址:

var urls = ['1.txt', '2.txt', '3.txt']; // these text files contain "one", "two", "three", respectively.

我想构建一个看起来像这样的对象:

And I want to build an object that looks like this:

var text = ['one', 'two', 'three'];

我一直在尝试使用 fetch 来学习如何做到这一点,当然它会返回 Promises.

I’ve been trying to learn to do this with fetch, which of course returns Promises.

我尝试过的一些事情不起作用:

var promises = urls.map(url => fetch(url));
var texts = [];
Promise.all(promises)
  .then(results => {
     results.forEach(result => result.text()).then(t => texts.push(t))
  })

这看起来不对,无论如何它都不起作用——我最终没有得到一个数组 ['one', 'two', 'three'].

This doesn’t look right, and in any case it doesn’t work — I don’t end up with an array ['one', 'two', 'three'].

在这里使用 Promise.all 是正确的方法吗?

Is using Promise.all the right approach here?

推荐答案

是的,Promise.all 是正确的方法,但如果你想先fetch<,你实际上需要它两次/code> 所有 url,然后从中获取所有 text s(这也是响应正文的承诺).所以你需要做

Yes, Promise.all is the right approach, but you actually need it twice if you want to first fetch all urls and then get all texts from them (which again are promises for the body of the response). So you'd need to do

Promise.all(urls.map(u=>fetch(u))).then(responses =>
    Promise.all(responses.map(res => res.text()))
).then(texts => {
    …
})

您当前的代码不起作用,因为 forEach 不返回任何内容(既不是数组也不是承诺).

Your current code is not working because forEach returns nothing (neither an array nor a promise).

当然,您可以简化它,并在相应的 fetch 承诺完成后立即从每个响应中获取正文:

Of course you can simplify that and start with getting the body from each response right after the respective fetch promise fulfilled:

Promise.all(urls.map(url =>
    fetch(url).then(resp => resp.text())
)).then(texts => {
    …
})

或与 await 相同的事情:

const texts = await Promise.all(urls.map(async url => {
  const resp = await fetch(url);
  return resp.text();
}));

这篇关于如何使用 Promise.all 获取 URL 数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆