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?