在Node.JS(ES7)中的递归方法中使用async / await并行化调用

时间:2017-10-01 02:39:22

标签: javascript node.js recursion parallel-processing async-await

我在Node.JS 8.6.0中有类的以下方法:

async urlProcess(nodo,nivel,topenivel,conf){
try{  
  // some exiting conditions and  
  // some synchronous code around here
  // ..... 

   let DOM = await this.getDocumentData(url); //this methos returns Promise
   if(DOM){

    // More sequential code ,we have an array of URLs in let sons;
   // and finally we get this:

    // == SEQUENTIAL SOLUTION == //

    // for(let  urlHija of sons){
    //   await this.urlProcess(urlHija,nivel+1,topenivel,conf);
    // }

    // == PARALLEL SOLUTION == //
    let promises = [];

    for(let urlHija of sons){
      promises.push(this.urlProcess(urlHija,nivel+1,topenivel,conf));
    }
    await Promise.all(promises);

    return 0;

  }else
    return 0;

}catch(err){
  throw err;
}
}

当我测量两个解决方案的性能时,我得到的是顺序一个更快,所以我认为并行化由于某种原因不起作用。 我测量时间的方式是这样的:

async start(nivel,topenivel,payload) {
try {
  let nodo = this.arbol.getRaiz();
  console.time("performance");
  await this.urlProcess(nodo, nivel, topenivel, payload)
  console.timeEnd("performance");
  return 0;
}catch(err){
  throw err;
}
};

0 个答案:

没有答案