1

Suppose I've file named orders.js something like this:

exports.getOrders = function() {
    return {'a': 'b'};
}

and another file named report.js like this:

var Order = require('./src/orders');

console.log(Order.getOrders());

This will print {'a' : 'b'} and I'm happy. Now I want to make things more complicated, since I need to read data from a CSV (using fast-csv node package), so I modified the orders.js:

var csv = require('fast-csv');

exports.getOrders = function(clientId) {

    var orders = [];

    csv
    .fromPath("./data/orders.csv", {headers: true, delimiter:';'})
    .on("data", function(data) {
        orders.push({'price' : data.price});
        }
    })
    .on("end", function(){
        console.log(orders) // THIS WILL PRINT THE CORRECT ARRAY 
        return orders;
    });

    console.log(orders); // THIS WILL PRINT AN EMPTY ARRAY
    return orders;
}

How can I return the correct array when Order.getOrders() is invoked in report.js?

BAD_SEED
  • 4,840
  • 11
  • 53
  • 110

1 Answers1

1

there are many async functions, you can use but for this i used waterfall method

you could do like this

1.report.js

var Order = require('./src/orders');
var c = 0;

Order.getOrders(c, function(err, d ) {
        console.log('err', err, 'd', d);
        // do what you want to do with response 'd'
        // this will print an array of results
        // argument c is value for clientId parameter, use your 
        // value or data
});

2. order.js

var csv = require('fast-csv');
var async = require('async')
exports.getOrders = function (clientId, cb) {

async.waterfall([
    function (callback) {
        var orders = [];
        csv.fromPath("./data/orders.csv", { headers: true, delimiter: ';' })
            .on("data", function (data) {
                orders.push({ 'price': data.price });
            })
            .on("end", function () {
               return callback(null, orders)
            });

    }
], function(err, d) {
    if(err) return cb(err);
    cb(null, d)
 })
}
parwatcodes
  • 6,669
  • 5
  • 27
  • 39