Ando Ando - 1 year ago 69
Javascript Question

create a json object with responses from different async functions

My goal is to create a JSON object, from a paragraph of text, that I can then insert as a document into MongoDB. I'm using nodejs and wanted to go for the async approach.

My JSON has parameters like so


My logic is this

create a module with async functions that parse the text and extract weight and height using regex.

but then how would I combine all the responses from these functions into one JSON that I can import at once?

I'm thinking something like this

var get_height = require().height;
var get_weight = require().weight;

exports.contr = function(){
var height,
get_height(text, function(err, res){

get_weight(text, function(err, res){
//All other async functions
combine_json(height, weight, ... , function(err, res){

console.log(res); //the json was successfully inserted into mongoDB

I find async confusing and in the above example I'm not sure about two things

  1. wouldn't
    run without waiting for the data from the previous two functions (weight, height)

  2. what is the best practice to handle such cases? Should i just use sync functions and wait top-to-bottom for each one to do its thing and then run the final one or I can leverage async?

Answer Source

The simplest way to wait for the results of two independent asynchronous functions is to use promises and Promise.all. For this we'll assume get_height and get_weight return a Promise and can be used as such:

get_height().then(function (height) { console.log(height); });

Then it's trivial to combine two of those promises:

Promise.all([get_height(), get_weight()]).then(function (results) {
    combine_json(results[0], results[1]);

See for documentation and details.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download