js异步函数之间并行操作(promise)

Nodejs评论638阅读模式
摘要

js/nodejs异步函数之间并行操作(promise)

 

var Async = require('async');
function f1 (para1) {
  return new Promise((resolve1 ,reject1) => {
    setTimeout(function () {
      console.log("f1:"+ para1);
      resolve1(f2(para1+10));
    },1000);
  })
}

function f2 (para2) {
  return new Promise((resolve2,reject2) => {
    Async.parallel([
      function(callback){
        setTimeout(function () {
          console.log("paraX:"+para2);
          callback(null,"callback1");
        },2000);
      },
      function (callback) {
        setTimeout(function () {
          console.log("paraY:"+para2);
          callback(null,"callback2");
        },2000);
      },
    ],function (err,res) {
      if(err){
        reject2(new Error(err))
      }else {
        console.log("arry:"+res);  // 来自callback1和callback2的数据
        resolve2(res);
        // 执行下面内容
      }
    });
  })
}

(async () => {
  for (let i=0;i<5;i++){
    await f1(i).then(res => {
      console.log("------------"+res)
    }).catch(e => {
      console.log("============"+e)
    })
  }
})()

Nodejs最后更新:2020-11-6