Synchronization of nodejs implementation methods

1. What I recommend is the class library: async  click to jump to the official documentation.

 

2. The method to achieve synchronization: async.series This method can realize the synchronous execution of multiple functions. For example:

async.series([
        function(callback){
          function one
        },
        function(callback) {
          function two
        }
      ],
      function(err,results){
        So the callback when the function execution completes or an error occurs.
      })

  The first parameter is an array representing the function to be executed. The second parameter is the callback function.

 

3. Implement the synchronization of the loop. async.concat This method can be implemented. For example:

async.concat(note_info, function (item, callback) { },function (err, data) {});

 The method has three parameters, the first parameter can be an array or an object. The second parameter is a function, which mainly handles the first parameter. The third parameter is the callback function.

 

4. Combined with the specific examples of the above implementation:

async.series([
        function(callback){
          note.get(null,function(err,data) {
            if (err) {
              return res.json({status: 500, message: 'Background error'})
            }
            note_info = data;
            callback(null,data)
          })
        },
        function(callback) {
          async.concat(note_info,
              function (item, callback) {
                register.get({_id: new ObjectID(item.user)}, function (err, user) {
                  if (err) {
                    return res.json({status: 500, message: 'Background error'})
                  }
                  if (user && user.length > 0) {
                    item.user = user;
                    callback(null, item)
                  }
                });
              },
              function (err, data) {
                callback(null,data)
              });
        }
      ],
      function(err,results){
        res.json({status: 200, data: results[0]})
      })

 

The above is an example that needs to first fetch the data from the note, then fetch the data from the   register according to the data in the note, and finally combine the data. 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326640540&siteId=291194637