等待异步回调返回值
问题描述:
的fileA之前
userID = (userName) ->
id = 0
someAPI.getUser userName, (err, data, res) ->
id = data.id if data
console.log id # Outputs ID
return
id
console.log userID('someUsername') # Outputs 0
FILEB
getUser: (username, callback) ->
return api.get 'users/show', { 'username': username }, callback
我怎样才能console.log userID('someUsername')
输出ID为好,而不是0?即请在返回ID之前等待。
我曾尝试随机包装与Meteor.wrapAsync和Meteor.bindEnvironment的东西,但似乎无法得到任何地方。
答
谢谢大家。我发现一个解决方案使用https://github.com/meteorhacks/meteor-async
getUserID = Async.wrap((username, callback) ->
someAPI.getUser username, (err, data, res) ->
callback err, data.id
)
console.log getUserID('someUsername')
答
您可以做到在回调的工作或控制与承诺或事件发射流程:
"use strict";
var Q = require('q');
var EventEmitter = require('events').EventEmitter;
// using a promise
var defer = Q.defer();
// using an emitter
var getUserID = new EventEmitter();
var id = 0;
getUser("somename", function (err, data, res) {
if (data)
id = data.id;
// simply do the work in the callback
console.log("In callback: "+data.id);
// this signals the 'then' success callback to execute
defer.resolve(id);
// this signals the .on('gotid' callback to execute
getUserID.emit('gotid', id);
});
console.log("oops, this is async...: "+id);
defer.promise.then(
function (id) {
console.log("Through Promise: "+id);
}
);
getUserID.on('gotid',
function (id) {
console.log("Through emitter: "+id);
}
);
function getUser (username, callback) {
setTimeout(function() {
callback(null, { id : 1234 }, null);
}, 100);
}
把它放在'someAPI.getUser'的回调中。 – Pointy 2014-10-01 15:22:11
欢迎来到异步的奇妙世界,你不能那样做。请参阅相关http://stackoverflow.com/q/23667086/1331430 – 2014-10-01 15:29:25
与流星相关的答案是使用期货。阅读[this](https://www.discovermeteor.com/patterns/5828399)和[this](https://gist.github.com/possibilities/3443021)。 – richsilv 2014-10-01 15:41:49