假设我有一个数组,我想对数组的每个元素执行异步函数。
let a = [x1, x2, x3]
// I want to
await a.forEach(async (x) => {...})
// which equals to
let fn = async (x) => {...}
await fn(x1)
await fn(x2)
await fn(x3)
我怎样才能做到这一点?
像这样?
for (let x of a) {
await fn(x);
}
或者,如果您真的不喜欢创建一个单独的fn
:
for (let x of a) {
await (async v => {
...
})(x);
}
你甚至可以将它添加到Array.prototype
:
Array.prototype.resolveSeries = async function(fn) {
for (let x of this) {
await fn(x);
}
}
// Usage:
await a.resolveSeries(fn);
// Or:
await a.resolveSeries(async x => {
...
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)