相关疑难解决方法(0)

如何使用Promise.all获取URL数组?

如果我有一个网址数组:

var urls = ['1.txt', '2.txt', '3.txt']; // these text files contain "one", "two", "three", respectively.
Run Code Online (Sandbox Code Playgroud)

我想构建一个如下所示的对象:

var text = ['one', 'two', 'three'];
Run Code Online (Sandbox Code Playgroud)

我一直在努力学习如何做到这一点fetch,这当然会回归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))
  })
Run Code Online (Sandbox Code Playgroud)

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

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

javascript promise es6-promise fetch-api

46
推荐指数
4
解决办法
4万
查看次数

标签 统计

es6-promise ×1

fetch-api ×1

javascript ×1

promise ×1