promise + reduce = sequential execution

59 阅读1分钟

3 ways to implement the same function

for (let i = 0; i < repeatTimes; i++) {
    for (let j = 0; j < nlpHeadlines.length; j++) {
        if (waitGapInMilliseconds > 0) await sleep(waitGapInMilliseconds);
        const refreshedHeadline = refreshHeadline(nlpHeadlines[j], i);
        await publish(refreshedHeadline);
    }
}
for (let i = 0; i < repeatTimes; i++) {
    await nlpHeadlines.reduce(async (prom, nlpHeadline) => {
        await prom;
        if (waitGapInMilliseconds > 0) await sleep(waitGapInMilliseconds);
        const refreshedHeadline = refreshHeadline(nlpHeadline, i);
        await publish(refreshedHeadline);
    }, Promise.resolve());
}
for (let i = 0; i < repeatTimes; i++) {
    await nlpHeadlines.reduce((promise, nlpHeadline) => {
        return promise.then(async () => {
            if (waitGapInMilliseconds > 0) await sleep(waitGapInMilliseconds);
            const refreshedHeadline = refreshHeadline(nlpHeadline, i);
            await publish(refreshedHeadline);
        });
    }, Promise.resolve());
}

to replace this outer loop, that more difficult because there is no build it "do X time" high order function (sadly) we can either let it as it is, or use Array(repeatTimes).fill(0).reduce((acc, _, i) => { })

await Array(repeatTimes)
    .fill(0)
    .reduce(async (acc, _, i) => {
        await acc;
        await nlpHeadlines.reduce((promise, nlpHeadline) => {
            return promise.then(async () => {
                if (waitGapInMilliseconds > 0) await sleep(waitGapInMilliseconds);
                const refreshedHeadline = refreshHeadline(nlpHeadline, i);
                await publish(refreshedHeadline);
            });
        }, Promise.resolve());
    }, Promise.resolve());