从每个回调调用中获取异步nodejs值[重复]
Posted
技术标签:
【中文标题】从每个回调调用中获取异步nodejs值[重复]【英文标题】:getting async nodejs value from each callback calls [duplicate] 【发布时间】:2017-04-28 17:22:49 【问题描述】: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:请帮忙。
【问题讨论】:
看看***.com/q/14220321/5692251 【参考方案1】:async
是 ES7 中的保留字,以后实现时可能会给您带来问题。
您可能要考虑的实际上是将 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)
【讨论】:
【参考方案2】:我希望这对大多数人来说是一个改变游戏规则的解决方案。这使得 ASYC java 回调变成了看起来与高效回调处理同步的东西。这是我三天的挑战。 Callbacks 确实是 javacript 中的一个主要挑战,这里是如何使用 Promise 解决问题。
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
)
终于成功了。干杯! Daniel Adenew
【讨论】:
以上是关于从每个回调调用中获取异步nodejs值[重复]的主要内容,如果未能解决你的问题,请参考以下文章