[英]JavaScript: how can I tweak this function to return all the results from the async functions in order
I have a function that takes an array of async/sync functions and invoke each of them sequentially (as opposed to in parallel) in the same order as the input is passed.我有一个 function,它采用异步/同步函数数组,并按照与传递输入相同的顺序顺序(而不是并行)调用它们中的每一个。
For example:例如:
const sleep = (delay) => new Promise((r) => setTimeout(r, delay)) const fn1 = async () => { await sleep(2000) console.log('fn1') return 'fn1' } const fn2 = async () => { await sleep(3000) console.log('fn2') return 'fn2' } const fn3 = async () => { await sleep(1000) console.log('fn3') return 'fn3' } const fn4 = () => { console.log('fn4') return 'fn4' } function serializeAsyncFns(fns) { return fns.reduce( (promise, fn) => promise.then(() => fn()), Promise.resolve() ) } serializeAsyncFns([fn1, fn2, fn3, fn4]) // fn1 -> fn2 -> f3 -> f4
But now the return value of serializeAsyncFns
is a promise that resolves to the return value of the last function in the input list, which is f4
.但是现在serializeAsyncFns
的返回值是一个 promise,解析为输入列表中最后一个 function 的返回值,即f4
。 Is there a way to tweak this funciton so that the returned promise resolves to the an array of values of all the functions, in order of how they got passed.有没有办法调整这个函数,以便返回的 promise 解析为所有函数的值数组,按照它们如何传递的顺序。
In this case it would be ['fn1', 'fn2', 'fn3', 'fn4']
在这种情况下,它将是['fn1', 'fn2', 'fn3', 'fn4']
Promise.all
doesn't work here as it would fire all the promises in parallel. Promise.all
在这里不起作用,因为它会并行触发所有承诺。
easiest way is with a for loop and async/await最简单的方法是使用 for 循环和 async/await
async function serializeAsyncFns(fns) {
const result = [];
for (const fn of fns) {
result.push(await fn());
}
return result;
}
If, for some reason you can't use async/await for that function, this is what I used to do before async/await was a thing如果由于某种原因你不能为那个 function 使用 async/await,这就是我在 async/await 出现之前所做的事情
const serializeAsyncFns = fns =>
fns.reduce((promise, fn) =>
promise.then(results => Promise.resolve(fn()).then(result => [...results, result])),
Promise.resolve([])
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.