在返回值之前等待异步回调

时间:2014-10-01 15:21:05

标签: javascript node.js meteor coffeescript

使用

的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随机包装,但似乎无法到达任何地方。

2 个答案:

答案 0 :(得分:1)

您可以在回调中完成工作,也可以使用promise或事件发射器控制流程:

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

答案 1 :(得分:1)

谢谢大家。我找到了使用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')