在另一个函数中使用异步 [英] Using Async inside another function

查看:55
本文介绍了在另一个函数中使用异步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用node.js并与sails.js框架异步.我正在尝试创建一个对数据数组执行一些异步DB操作的函数,但是在找出一种简单的方法将异步结果返回给父函数时遇到了问题.这是我的代码:

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!!

推荐答案

使用Node 6.0,可以使用内置的Promises.

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);
}

要使用上述功能,

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

这篇关于在另一个函数中使用异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆