Search code examples
node.jsloopbackjs

Loopback: how to collect data in a for-loop containing a async method?


Using loopback I have a simple for loop in which I perform a findOne:

let my_data = [];
Orders.forEach(function(order,idx) {

  let postalcode = order.toJSON().customer.postal_code;
  let ps4 = postalcode.slice(0,4);

  app.models.postalcode.findOne({where: {postal_code: parseInt(ps4)},include: ['depot']}, function (err, Postalcode) {
    if (err) {
      winston.error('Could not load postalcode %s due to error %s: ', ps4, err.message);
    } else {

      if (Postalcode) {
        let depot = Postalcode.toJSON().depot;
        if (!depot) {
          //
        } else {
          let depot_city = depot.city;
          if (cities_to_process.indexOf(depot_city) > -1) {
            my_data.push(order);
          } else {

          }
        }
      } else {
        winston.warn('Could not find postal code %s', ps4)
      }
    }
  });
});

console.log(my_data);

After the for loop I would like to do something with the collected data in my_data. Since findOne appears to be asynchronous, what is the preferred way of doing this?


Solution

  • Use async library. It will be easy for you to use async.eachSearies() to loop the async functions in series and get the desired output. You can take a reference here link