简体   繁体   中英

node js async.parallel with await possible?

I have a problem with async.parallel in node js. Following code ist working perfect

  var data = {};

  data.task_1= function(callback) { 
    var res_1 = "hello 1";
    callback(null, res_1);
  }
  data.task_2 = function(callback) { 
    var res_2 = "hello 2";
    callback(null, res_2);
  }

  async.parallel(data, function(err, results) {
    if (err){
      console.log(err);
    }
    console.log(results);
  });

The result is: { task_1: 'hello 1', task_2: 'hello 2' }

But if I try to do the task with a function calling data from a database, I become following error: TypeError: callback is not a function and the result { task_2: 'hello 2', task_1: undefined }

I see in the log, that the data is retrieved before the json file is logged.

Here is my code:

  var data = {};

  data.task_1 = async function(callback) { 
    var res_1 = await getData("xyz");
    console.log(res_1);
    callback(null, res_1);
  }
  data.task_2 = function(callback) { 
    var res_2 = "hello 2";
    callback(null, res_2);
  }

  async.parallel(data, function(err, results) {
    if (err){
      console.log(err);
    }
    console.log(results);
  });

What do I miss? Thanks for any help!

You could return the result from getData(), this should work (according to the docs): https://caolan.github.io/async/v3/global.html#AsyncFunction , and you can use the await statement too:

var data = {};

data.task_1 = async function() { 
    var res_1 = await getData("xyz");
    console.log(res_1);
    return res_1;
}
data.task_2 = function(callback) { 
    var res_2 = "hello 2";
    callback(null, res_2);
}

async.parallel(data, function(err, results) {
    if (err){
        console.log(err);
    }
    console.log(results);
});

I believe it's because if we mark the function as async, no callback will be passed. So if I assign a non-async function and use.then(), the callback will be passed and all will work nicely: From the docs, "Wherever we accept a Node-style async function. we also directly accept an ES2017 async function, In this case. the async function will not be passed a final callback argument" Which explaints the error message "callback is not a function."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM