EdwardZZZ / articles

工作点滴记录
2 stars 0 forks source link

waterfall #29

Open EdwardZZZ opened 6 years ago

EdwardZZZ commented 6 years ago

const taskReducer = async (promise, action) => action(await promise);

const waterfall = async (tasks, init) => await tasks.reduce(taskReducer, init);

// eg
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const getSeconds = () => new Date().getSeconds();
async function asyncTask(i) {
    await sleep(3000);
    console.log(i);
    return getSeconds();
};

(async () => {
    await waterfall([asyncTask, asyncTask, asyncTask], getSeconds());
    console.log('---------');
})();

可以看做是简版的waterfall实现,和Promise.all乱序不同,这个是顺序执行

EdwardZZZ commented 3 years ago

[...Array(5)].forEach((_, i) => {
    excute(i);
});

function excute(n) {
    this.prev = this.prev ? this.prev.then(() => print(n)) : print(n);
    /*
    clearTimeout(this.timeout);
    this.taskList = this.taskList || [];
    this.taskList.push(n);
    this.timeout = setTimeout(async () => {
        for(const task of this.taskList) {
            await print(task)
        }
    }, 0);
    */
}

async function print(n) {
    await new Promise(resolve => setTimeout(resolve, Math.random() * 1e3));
    console.log(n);
}