gpt4 book ai didi

javascript - 返回值之前等待异步回调

转载 作者:行者123 更新时间:2023-12-02 16:56:30 25 4
gpt4 key购买 nike

文件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 随机包装内容,但似乎无济于事。

最佳答案

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

关于javascript - 返回值之前等待异步回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26144760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com