异步执行的ES6 reduce方法变为同步执行(ts)

背景:做一个业务时需要在reduce中执行async await,loadsh中也没找到,只能自己实现一个了

实现的方法
export const asyncReduce = async <T,K>(list:T[], fn:(preValue:K,val:T, idx:number) => Promise<K>, initData: K):Promise<K> => {
    let result:K = initData
    for (const key in list) {
        const item = list[key]
        result = await fn(result, item, Number(key))
    }
    return result
}
使用示例
const list = [1,2,3];

(async() => {
    const result = await asyncReduce(list, async(total, val) => {
        return total + val
    }, 0)
    console.log(result);
})() // 输出结果6

你可能感兴趣的:(es6,javascript,前端)