[removed] execute a bunch of asynchronous method with one callback

前端 未结 4 1528
半阙折子戏
半阙折子戏 2020-12-01 08:21

I need to execute a bunch of asynchronous methods (client SQLite database), and call only one final callback.

Of course, the ugly way is:

execAll : f         


        
4条回答
  •  一个人的身影
    2020-12-01 09:16

    Promises can help manage this. There are two general scenarios - parallel and serial. Parallel can be accomplished using Promise.all(), serial is more complex - task B can only start when task A is done. Here's a bare-bones sample:

    // returns a promise that resolves as the task is done
    const wrap = (fn, delay) => new Promise(resolve => setTimeout(_ => resolve(fn()), delay));
    const task = (fn, delay) => delay ? wrap(fn, delay) : Promise.resolve(fn());
    
    // given a list of promises, execute them one by one.
    const sequence = async l => l.reduce(async (a, b) => [].concat(await a, await b));
    
    const tasks = [
        task(_ => console.log("hello world")),
        task(_ => console.log("hello future"), 1000)
    ];
    
    sequence(tasks).then(_ => console.log("all done"));
    

    You may need some ES6/7 translation to make this work in browsers or older node versions.

提交回复
热议问题