0

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

mootrichard
  • 3,581
  • 13
  • 25
  • The idea with callbacks is that you just don't do anything after you've made the call, and then execute the callback function when the call is complete. To halt execution you simply don't have any code after the call. – Reinstate Monica Cellio Sep 14 '17 at 12:04

1 Answers1

0

I would highly suggest reviewing the documentation for the async library regarding AsyncFunction(). It looks like you are supposed to call the callback whether you have successfully completed your request or an Error has occurred.

Since the Shippo library is using 'when' for handling promise-like chaining (at the time of this writing, I have an open PR on GitHub to deprecate that to more normal promise chaining).

As a result of using 'when', it means that to catch errors you would pass .then() two functions, one for a success path and another for handling errors. It would work kind of like this:

shippo.track.get_status('usps', '1122334455667788')
      .then(function (results){
         // do stuff with your successful function call
      }, function (error) {
         // do stuff with the error you just received
      });

The reason that console.log('c') is printing out last, is because it won't execute that line until the original promise has resolved for retrieving the tracking status from Shippo.

Also, by calling the callback() in a setTimeout() function, you're only delaying each iteration from resolving by 3 seconds, but don't necessarily guarantee that your call on the shippo function was successful or not.

You should be calling the callback() function inside of each of the functions passed into then(). So that once you have received your results, you can resolve the instance of the function called by async.each(). By handling the callback() inside of the those functions, you can correctly handle successes and errors.

mootrichard
  • 3,581
  • 13
  • 25