数组的承诺与结果分开 [英] Array of promise with results separately
问题描述
基本上,我正在寻找类似 Promise.all()
的东西,但是在然后()$中调用该函数的东西c $ c>每个结果,一旦结果准备就绪。使用这样的标准回调(文件阅读示例)编写它是微不足道的:
Basically, I'm looking for something like Promise.all()
, but one that calls the function in then()
for each result, as soon as that result is ready. It's trivial to write using standard callbacks like this (file reading example):
function foo(files, bar) {
for (let file of files) {
const fr = new FileReader();
fr.onload = e => bar(e.target.result);
fr.readAsDataURL(file);
}
}
我确定有一个图书馆我想要的,但我想在纯JS中这样做。
I'm sure there's a library out there that does what I want, but I'd like to do that in pure JS.
为了澄清,我想要这样:
To clarify, I would like to have something like this:
function foo(files) {
// do something here;
}
foo(['1','2','3']).then(/* do something here with separate results */);`
推荐答案
只需使用 map
:
let read = file => return new Promise(resolve => {
const fr = new FileReader();
fr.onload = e => resolve(e.target.result);
fr.readAsDataURL(file);
});
Promise.all(files.map(file => read(file).then(bar)))
.then(allResultsFromBar => { /* use results array */ });
请注意, .then
促进从它承诺执行的功能(即它隐式调用 Promise.resolve
),所以 Promise.all
是无论什么 bar
返回,保证收到一系列承诺。
Note that .then
promotes anything returned from a function it executes to a promise (i.e. it calls Promise.resolve
on it implicitly), so Promise.all
is guaranteed to receive an array of promises no matter what bar
returns.
这篇关于数组的承诺与结果分开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!