How run async / await in parallel in Javascript

后端 未结 6 981
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 17:16

Finally async/await will be supported in all major browser soon except IE. So now we can start writing more readable code with async/<

6条回答
  •  执念已碎
    2020-11-30 17:55

    For those asking how you extend this to a run-time determined number of calls, you can use 2 loops. The first starts all the tasks, the second waits for everything to finish

    console.clear();
    
    function wait(ms, data) {
      return new Promise( resolve => setTimeout(resolve.bind(this, data), ms) );
    }
    
    /** 
     * While here we call the functions first,
     * then wait for the result later, so 
     * this will finish in 500ms.
     */
    async function runTasks(timings) {
      let tasks = [];
      for (let i in timings) {
          tasks.push(wait(timings[i], `Result of task ${i}`));
      }
    
      /* Want fast fail? use Promise.All */
      //return Promise.All(tasks);
      
      let results = [];
      for (let task of tasks) {
           results.push(await task);
      }
    
      return results;
    }
    
    async function taskRunner(fn, arg, label) {
      const startTime = performance.now();
      console.log(`Task ${label} starting...`);
      let result = await fn(arg);
      console.log(`Task ${label} finished in ${ Number.parseInt(performance.now() - startTime) } miliseconds with,`, result);
    }
    
    void taskRunner(runTasks, [50,100,200,60,500], 'Task List');

提交回复
热议问题