Undefined value after consultation with the bank

1

I have the following code:

var
    async = require('async'),
    pgPromise = require('../utils/pgPromise');

function anyFunction() {
    var tripItem = [];
    var tripStartEndTripItem = [];
    var tripStartEnd = [1,2,3];
    async.series({
        getIdDriver: function (callback) {
            callback(null, 'ok');
        },

        getFinishedTripsLogisticProvider: function (callback) {
            callback(null, 'ok');
        },

        getTrip: function (callback) {
            callback(null, 'ok');
        },

        getTripItem: function (callback) {
            var query = "select json_build_object ('trip_item', ti.*) from trip_item ti where ti_trip_id = ($1)";

            tripStartEnd.forEach(function(x) {
                pgPromise.db.any(query, [x.json_build_object.trip.tr_id])
                    .then(function(result) {
                       for(var i=0; i<result.length; i++) {
                            tripItem[i] = result[i].json_build_object.trip_item;
                        }

                        trip.trip_item = tripItem;

                        tripStartEndTripItem.push(trip);

                    }).catch(function (error) {
                        callback(error, null);
                    })
            });

            callback(null, tripStartEndTripItem);
       }

    }, function (err, results) {
        if (err) {
            console.log('error', err);
        } else {
            console.log(results);
        }
    });
}

The problem is when I assign the result (which is in the variable result ) of the query to the bank to the variable tripItem . When I try to print the result on the screen after the iteration of the tripStartEnd array, it results as a undefined value. It probably prints to the console before you finish the query. What could I do so that at the time of console.log(tripItem); , is the query value?

    
asked by anonymous 07.09.2016 / 14:18

1 answer

1

I think you need to use async.compose for what you need because the series does not exchange data between functions, they run serially but do not share data. Of course you can use global variables or within the shared scope, but this allows side effects and leaves the code less reliable.

Once you have the thread to pass data to the next function you can do so with Promise.All ():

function(tripStartEnd, callback) {
    var query = "select json_build_object ('trip_item', ti.*) from trip_item ti where ti_trip_id = ($1)";
    var queries = tripStartEnd.map(x => pgPromise.db.any(query, [x.json_build_object.trip.tr_id]));
    Promise.all(queries).then(arr => {
        const tripStartEndTripItem = arr.map(res => res.json_build_object.trip_item);
        callback(null, tripStartEndTripItem);
    }).catch(callback);
}

In this way, within the final callback of .compose you can receive the final data of the function string.

    
07.09.2016 / 19:23