【发布时间】:2015-06-22 23:01:29
【问题描述】:
我想使用新的 fetch api (https://fetch.spec.whatwg.org/) 一次获取多个文件。原生可以吗?如果是这样,我应该如何利用承诺?
【问题讨论】:
我想使用新的 fetch api (https://fetch.spec.whatwg.org/) 一次获取多个文件。原生可以吗?如果是这样,我应该如何利用承诺?
【问题讨论】:
var list = [];
var urls = ['1.html', '2.html', '3.html'];
var results = [];
urls.forEach(function(url, i) { // (1)
list.push( // (2)
fetch(url).then(function(res){
results[i] = res.blob(); // (3)
})
);
});
Promise
.all(list) // (4)
.then(function() {
alert('all requests finished!'); // (5)
});
这是未经测试的代码! 此外,它依赖于 Array.prototype.forEach 和 ES6 的新 Promise 对象。这个想法是这样的:
fetch API 获取它,将返回的 Promise 存储在 list 中。results中。list 中的所有 Promise 都已解决(即所有请求都已完成)时,该 Promise 将解决。results!【讨论】:
在 Kotlin 中实现 Boldewyn's solution 时,我将其缩减为:
fun fetchAll(vararg resources: String): Promise<Array<out Response>> {
return Promise.all(resources.map { fetch(it) }.toTypedArray())
}
这在 JavaScript 中大致翻译为:
function fetchAll(...resources) {
var destination = []
resources.forEach(it => {
destination.push(fetch(it))
})
return Promise.all(destination)
}
之前,我尝试使用 map 而不是 forEach + pushing 到一个新数组,但由于某种原因根本不起作用。
【讨论】: