2014-10-01 225 views
0

隨着等待異步回調返回值

的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

把它放在'someAPI.getUser'的回調中。 – Pointy 2014-10-01 15:22:11

+1

歡迎來到異步的奇妙世界,你不能那樣做。請參閱相關http://stackoverflow.com/q/23667086/1331430 – 2014-10-01 15:29:25

+2

與流星相關的答案是使用期貨。閱讀[this](https://www.discovermeteor.com/patterns/5828399)和[this](https://gist.github.com/possibilities/3443021)。 – richsilv 2014-10-01 15:41:49

回答

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') 
1

您可以做到在回調的工作或控制與承諾或事件發射流程:

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