Using Async inside another function [duplicate]

爱⌒轻易说出口 提交于 2019-12-25 16:48:42

问题


I am using node.js and async with sails.js framework. I am trying to create a function that perform some async DB operations on an array of data but I have problems figuring out a simple way to return the results of async to the parent function. Here's my code:

convertProductfields: function (articlesFromAurelia){

    async.each(articlesFromAurelia, function (post, cb) {
      Categories.find({name: post.Categoria})
        .then(function(category){

          post.cat_id = category[0].cat_id;              
          cb();
        })
        .fail(function(error){
          cb(error);
        })
    }, function(error){
      if(error) return res.negotiate(error);

      sails.log.debug('articlesFromAureliaModified ' , articlesFromAurelia);
      return articlesFromAurelia;
    });

    sails.log.debug('articlesFromAureliaNotModified ' , articlesFromAurelia);
    return articlesFromAurelia;
}

The problem of course is the execution order of the code. My function has already returned when the results of Async operations are available.... so, how to make it work? Thanks!!


回答1:


Using Node 6.0, in built Promises can be used.

convertProductfields: function (articlesFromAurelia){

    var allPromises = articlesFromAurelia
                      .map(post => new Promise((resolve, reject) => {
                               Categories.find({name: post.Categoria})
                                .then((category) => resolve(category))
                                .fail((error) => reject(error))
                               }));
    return Promise.all(allPromises);
}

And to use the above function,

convertProductfields(articlesFromAurelia)
  .then(() =>{
       //handle success
  }).catch(() => {
       //handle error
  })



回答2:


Hope it helps you.

convertProductfields: function (articlesFromAurelia, callback){

  async.each(articlesFromAurelia, function (post, cb) {
    Categories.find({name: post.Categoria})
      .then(function(category){
        post.cat_id = category[0].cat_id;
        cb();
      })
      .fail(function(error){
        cb(error);
      })
  }, function(error){
    if(error) 
      return callback(null);  //incase of error, return null

    sails.log.debug('articlesFromAureliaModified ' , articlesFromAurelia);
    return callback(articlesFromAurelia);  //return updated articles
  });
}


来源:https://stackoverflow.com/questions/41567117/using-async-inside-another-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!