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

查看:198
本文介绍了如何使用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 ,当然返回 Promise s。

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 是正确的方法,但是你实际上需要它两次,如果你想先获取所有网址,然后从他们那里获得所有文本 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(fetch)).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).

当然,你可以简化这一点,然后在完成相应的获取承诺后立即从每个响应中获取正文:

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 => {
    …
})

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

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