仓库源文站点原文


layout: post title: 用 Promise 实现 eachSeries

tags: [tools,javascript]

asynceachSeries 方法实现了多个异步方法的顺序调用,一次只执行一个异步方法。

const coll = [1, 2, 3, 4];
const iteratee = (item, cb) => {
    setTimeout(() => {
        console.log(item);
        cb();
    }, 200);
};
async.eachSeries(coll, iteratee, function (err) {
    // done
});

I don't need async.

如果不用 async,用 Promise,应该怎么实现呢?

const coll = [1, 2, 3, 4];
const iteratee = (item, cb) => {
    setTimeout(() => {
        console.log(item);
        cb();
    }, 200);
};
const series = Promise.resolve();
coll.forEach((item) => {
    series.then(() => {
        return new Promise((resolve, reject) => {
            iteratee(item, resolve);
        });
    });
});
series.then(() => {
    // done when ok
}).catch((err) => {
    // done when error
});

参考资料