Joj*_*oji 1 javascript asynchronous promise async-await
我有一个函数,它接受一组异步/同步函数,并按照输入传递的顺序依次调用每个函数(而不是并行)。
例如:
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 -> f4Run Code Online (Sandbox Code Playgroud)
但现在 的返回值serializeAsyncFns是一个 Promise,它解析为输入列表中最后一个函数的返回值,即f4。有没有办法调整这个函数,以便返回的承诺解析为所有函数的值数组,按照它们传递的顺序。
在这种情况下,它将是['fn1', 'fn2', 'fn3', 'fn4']
Promise.all在这里不起作用,因为它会并行触发所有承诺。
最简单的方法是使用 for 循环和 async/await
async function serializeAsyncFns(fns) {
const result = [];
for (const fn of fns) {
result.push(await fn());
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
如果由于某种原因你不能使用 async/await 来实现该功能,这就是我在 async/await 出现之前所做的事情
const serializeAsyncFns = fns =>
fns.reduce((promise, fn) =>
promise.then(results => Promise.resolve(fn()).then(result => [...results, result])),
Promise.resolve([])
);
Run Code Online (Sandbox Code Playgroud)