在forEach循环后直接添加回调不起作用。我是node.js的新手,所以任何帮助都会受到赞赏,谢谢。
这是一个Minecraft机器人,记录玩家登录和注销时间。在我从服务器被踢之后,我想在尝试重新加入之前结束所有玩家会话但是在下面的代码中,即使我使用async.series
它仍然不等到第一个函数完成 - 这是由于回调的位置?
bot.on('kicked', function(reason) {
console.log("I got kicked for", reason, "lol");
var timestamp = getTimestamp();
async.series([
function(callback) {
console.log("logging out all players");
logoutAllPlayers(timestamp, function(finished) {
console.log("logged out all players " + finished);
if (finished) {
callback();
}
});
},
function(callback) { //don't execute until previous function has run completely
//rejoin here
bot = mineflayer.createBot(options);
bindlisteners(bot);
}
]);
});
...
回调的正确位置在哪里?
function logoutAllPlayers(timestamp, callback) {
findOnlinePlayers(function(onlinePlayers) {
if (onlinePlayers.length > 0) {
onlinePlayers.forEach(function(player) {
var playerId = player.id;
var username = player.username;
async.waterfall([
function(callback) { //add logout event
addEvent(playerId, 2, timestamp, function(logoutEventId) {
console.log("[" + timestamp + "] " + "Created logout: " + logoutEventId + " for " + username + " (" + playerId +")");
callback(null, logoutEventId);
});
},
function(logoutEventId, callback) { //find players current session
findSession(playerId, function(sessionId, loginEventId) {
console.log("[" + timestamp + "] " + "Found session: " + sessionId +" for " + username + " (" + playerId +")");
callback(null, sessionId, loginEventId, logoutEventId);
});
},
function(sessionId, loginEventId, logoutEventId, callback) { //get timestamps for login and logout events to find the duration of session
findEventTimestamp(loginEventId, function(loginTimestamp) {
findEventTimestamp(logoutEventId, function(logoutTimestamp) {
var difference = diffBetweenTimestamps(loginTimestamp, logoutTimestamp);
console.log("[" + timestamp + "] " + "Duration: " + difference + " for " + username);
callback(null, sessionId, logoutEventId, difference, callback);
});
});
},
function(sessionId, logoutEventId, difference, callback) { //end session and update online status
endSession(sessionId, logoutEventId, difference, function(callback) {
console.log("[" + timestamp + "] " + "Updated session: " + sessionId + " for " + username + " (" + playerId +")");
updatenOnlineStatus(playerId, false);
});
}
]);
});
callback(true);
}
});
}
答案 0 :(得分:5)
在logoutAllPlayers
中,您在callback(true);
来电已完成步骤之前致电async.waterfall
。
相反,您应该从callback
调用最终瀑布//end session and update online status
,然后更改瀑布的最后一行以进行完成回调。
async.waterfall([
// ...
], function(){
callback(true);
});