【问题标题】:Waiting for async callback before returning a value在返回值之前等待异步回调
【发布时间】:2014-11-26 11:51:24
【问题描述】:

文件A

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

文件B

getUser: (username, callback) ->
  return api.get 'users/show', { 'username': username }, callback

我怎样才能让console.log userID('someUsername') 也输出 ID,而不是 0? IE。在返回 id 之前让它等待。

我尝试过使用 Meteor.wrapAsync 和 Meteor.bindEnvironment 随机包装东西,但似乎无法到达任何地方。

【问题讨论】:

  • 把它放在someAPI.getUser的回调里面。
  • 欢迎来到异步的奇妙世界,你不能那样做。查看相关stackoverflow.com/q/23667086/1331430
  • 与 Meteor 相关的答案是使用 Futures。阅读thisthis

标签: javascript node.js meteor coffeescript


【解决方案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')

【讨论】:

    【解决方案2】:

    您可以在回调中完成工作,也可以使用 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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-13
      • 2011-01-06
      • 1970-01-01
      • 2020-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多