Search code examples
asynchronousloopbackjs

How to call cb function after async function finished in loopback 3


I worked at a loopback project.
Here I'm making extended api in the model.
There are many async functions.
I want to call cb function after all async functions called.
Anyone have idea to do it?


Solution

  • Use async.parallel that run function parallel and return final results.

    Below example help you:

    var async = require('async')
    
    
      function functionName(parameter, cb) {
            async.parallel([
              function(callback) {
                  setTimeout(function() {
                      callback(null, 'one');
                  }, 200);
              },
              function(callback) {
                  setTimeout(function() {
                      callback(null, 'two');
                  }, 100);
              }
          ],
          // optional callback
          function(err, results) {
              // the results array will equal ['one','two'] even though
              // the second function had a shorter timeout.
              if (error) {
                logger.error("ERROR FIRST SUBSCRIPTION > ", error);
                cb(error);
                return;
            }
            cb(null, {
                success: true
            });
          });
    };
    

    reference Link: async