I'm passing an array to async.each()
, where the execution will pass through the if
condition, it adds the items to the array when the condition is satisfied while entering into the else
statement, the execution will not wait for the shippo response. It moves into the next line and sends the response to the server.
I noticed that we are getting the response from shippo
a few seconds later, so I placed a setTimeout()
function after the completion of else
block, but even in my console the message 'c'
will print last. I'm very much confused with the callbacks, how they will work. Is there any other way to the halt the execution flow till we get the response from shippo
.
var async = require('async');
import each from 'async/each';
async.each(trackingnumbers, function (value, callback) {
value['TrackingNo'] = parseInt(value['TrackingNo']);
value['Provider'] = value['Provider'].toLowerCase();
if (value['Provider'] == "domestic") {
items.push({ 'TrackingNo': value['TrackingNo'], 'Provider': value['Provider'], 'Status': 'Completed' });
console.log('a');
}
else {
console.log('b');
shippo.track.get_status(value['Provider'], value['TrackingNo']).then(function (status) {
console.log('c');
items.push({ 'TrackingNo': value['TrackingNo'], 'Provider': value['Provider'], 'Status': status.tracking_status });
}, functionconsole.log('d'); (err) {
console.log("There was an error retrieving tracking information: %s",+ err);
callback('There was an error retrieving tracking information:');
//
});
console.log('d');
e }
console.log('e');
setTimeout(function(){
callback();
},3000);
}, function (err) {
if (err) {
console.log('error occured ' + '|' + err);
}
else {
console.log(items);
res.setHeader("Access-Control-Allow-Origin", "*");
res.send(items).status('200');
}
});
Here is my output along with the shippo response after we placed an timeout function