从每个回调调用获取异步nodejs值[duplicate]

qyuhtwio  于 2023-01-30  发布在  Node.js
关注(0)|答案(2)|浏览(120)
    • 此问题在此处已有答案**:

(41个答案)
6年前关闭。

var async = require('async');

var square = function (id, callback) {
  Business.prototype.getBusinessUser(id,function(userObject){
    return callback(userObject);
  });
 };

async.eachSeries(findBusinessResult, function (businessObject, callback) {
//console.log("results from square");
  var result =  square(businessObject["id"] , function(result){
    console.log(result);
  });
  callback(); // Alternatively: callback(new Error());
 }, function (err,results) {
   if (err) { throw err; }
   console.log('Well done :-)!');
   console.log(results);
});

为什么结果总是变成 * undefined *:请帮忙。

c0vxltue

c0vxltue1#

async是ES 7中的保留字,在以后实现时可能会给您带来问题。
你可能需要考虑的是实际上使用async/await和babel。
一些浏览器已经开始实现它了

var square = id => 
    new Promise(rs => 
        Business.prototype.getBusinessUser(id, rs)
    )

async search() {
    for (let businessObject of findBusinessResult) {
        let result = await square(businessObject.id)
        console.log(result)
    }
}
w46czmvw

w46czmvw2#

我希望这对大多数ppl来说是一个改变游戏规则的解决方案。这使得ASYC java回调看起来像是与有效的回调处理同步的东西。这是我三天的挑战。[回调][1]确实是javacript中的一个主要挑战,这里是如何使用承诺来解决问题。

install bluebird 
npm install bluebird --save

//在您的代码中

var Promise = require('bluebird'); //yeah awsome bird indeed :)

function extendBusinessObjectPromise(id,element) {
    return new Promise(function(resolve, reject) {
        Business.prototype.getBusinessUser( id ,function(userObject){
         var extend = require('util')._extend;
         mergedJson = userObject;
         elements = element;
         extend({},elements);
         extend(elements,mergedJson);
         global.businesssWithUsers.push(elements); //sahred object
        resolve(global.businesssWithUsers)
        })
})

}

//NOW如何在foreach循环中调用promise结果,并将其值作为回调结果返回。这个想法似乎很疯狂:(

Person.prototype.getPersons = function(filter , callback) {
  //this my own Bill count since i have one using one user account
  global.businesssWithUsers = [];
  
models.PersonModel.findAll(filter_combined).then(function (findBusinessResult) {
  global.businesssWithUsers = []
  var extend = require('util')._extend;
  var mergedJsonArray =  [];

  if (findBusinessResult==null) {
    return callback(false,"no result found");
   }

   var promiseBusinessResult = null; //promise reslover :)

   var findBusinessResult =JSON.parse(JSON.stringify(findBusinessResult));

    findBusinessResult.forEach(function(eachElement) {
      var id = element["userId"];
      promiseBusinessResult = extendBusinessObjectPromise(id,element);
    });

    promiseBusinessResult.done(function(result){
       callback(true,result); //pass the result to main function
     });

    }).catch(function (err) {
      log.error(err["errors"][0]["message"])
      callback(false,err["errors"][0]["message"])
      return
    })
}

终于成功了干杯!

相关问题