nodejs,异步进行reduce,await不等待promise解析

时间:2019-02-11 07:58:14

标签: node.js async-await

我不明白为什么所有承诺都在同一时间得到解决的原因。 我读到awaitforEach循环中无法正常工作,但在map上也不能正常工作

const promise = async (ms, name) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log(`resolving ${name}`)
            resolve(name)
        }, ms)
    });
}

async function main() {
    ['foo', 'bar', 'baz'].reduce(async (accum, curr) => {
        const res = await promise(1000, curr)
        return res
    }, Promise.resolve(''))
}

main()

但是在这种情况下,await工作正常:

async function main2() {
    const ms = 1000
    await promise(ms, "foo")
    await promise(ms, "bar")
    await promise(ms, "baz")
}

main2()

1 个答案:

答案 0 :(得分:2)

reduce回调的每个迭代将同步初始化。您需要等待上一次迭代中的累加器(幸运的是已经是Promise)才能解决,然后再运行reduce回调的主体:

const promise = async (ms, name) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log(`resolving ${name}`)
            resolve(name)
        }, ms)
    });
}

async function main() {
    ['foo', 'bar', 'baz'].reduce(async (accum, curr) => {
        // don't progress further until the last iteration has finished:
        await accum;
        const res = await promise(1000, curr)
        return res
    }, Promise.resolve(''))
}

main()