javascriptnode.jsswagger-node-express

Data passing in async.waterfall model is not working?


I want to pass the data 1 and data 2 to the last function directly. It is working when I pass data 1 to second function and from there data 1 + data 2 to the last function. But the problem is that I don't want to pass data 1 to the second function. Can we do it with 'asyc.series' and 'async.parallel'?.

 var fs = require("fs");
    var async = require('async');
    async.waterfall([
        myFirstFunction,
        mySecondFunction,            

    ], function (err,data1,data2) {
        var values={'data1':data1,'data2':data2,'msg':"hai"}
       console.log("values: %j", values);
    });
    function myFirstFunction(callback) {
          fs.readFile('file1.js','utf8',function(err,data1){
          callback(null,data1);
           });
    }
    function mySecondFunction(callback) {
         fs.readFile('file2.js','utf8',function(err,data2){
          callback(null,data2);
          });
    }

Solution

  • You should do it with async.parallel

    var fs = require("fs");
    var async = require('async');
    async.parallel([
        myFirstFunction,
        mySecondFunction,            
    
    ], function (err, results) {
        if(err) console.error(err);
        var data1 = results[0];
        var data1 = results[1];
    });
    
    function myFirstFunction(callback) {
        fs.readFile('file1.js','utf8',function(err,data1){
            callback(null,data1);
        });
    }
    
    function mySecondFunction(callback) {
        fs.readFile('file2.js','utf8',function(err,data2){
            callback(null,data2);
        });
    }