【发布时间】:2017-04-23 11:25:07
【问题描述】:
我的问题是代码似乎没有按顺序运行,如下所示。
此代码适用于我正在创建的 discord.js 机器人。
var Discord = require("discord.js");
var bot = new Discord.Client();
var yt = require("C:/Users/username/Documents/Coding/Discord/youtubetest.js");
var youtubetest = new yt();
var fs = require('fs');
var youtubedl = require('youtube-dl');
var prefix = "!";
var vidid;
var commands = {
play: {
name: "!play ",
fnc: "Gets a Youtube video matching given tags.",
process: function(msg, query) {
youtubetest.respond(query, msg);
var vidid = youtubetest.vidid;
console.log(typeof(vidid) + " + " + vidid);
console.log("3");
}
}
};
bot.on('ready', () => {
console.log('I am ready!');
});
bot.on("message", msg => {
if(!msg.content.startsWith(prefix) || msg.author.bot || (msg.author.id === bot.user.id)) return;
var cmdraw = msg.content.split(" ")[0].substring(1).toLowerCase();
var query = msg.content.split("!")[1];
var cmd = commands[cmdraw];
if (cmd) {
var res = cmd.process(msg, query, bot);
if (res) {
msg.channel.sendMessage(res);
}
} else {
let msgs = [];
msgs.push(msg.content + " is not a valid command.");
msgs.push(" ");
msgs.push("Available commands:");
msgs.push(" ");
msg.channel.sendMessage(msgs);
msg.channel.sendMessage(commands.help.process(msg));
}
});
bot.on('error', e => { console.error(e); });
bot.login("mytoken");
youtubetest.js 文件:
var youtube_node = require('youtube-node');
var ConfigFile = require("C:/Users/username/Documents/Coding/Discord/json_config.json");
var mybot = require("C:/Users/username/Documents/Coding/Discord/mybot.js");
function myyt () {
this.youtube = new youtube_node();
this.youtube.setKey(ConfigFile.youtube_api_key);
this.vidid = "";
}
myyt.prototype.respond = function(query, msg) {
this.youtube.search(query, 1, function(error, result) {
if (error) {
msg.channel.sendMessage("There was an error finding requested video.");
} else {
vidid = 'http://www.youtube.com/watch?v=' + result.items[0].id.videoId;
myyt.vidid = vidid;
console.log("1");
}
});
console.log("2");
};
module.exports = myyt;
正如代码所示,我有一个机器人能够处理的命令的对象,并且我有一个函数可以在收到消息时运行所述命令。 在整个代码中,您可以看到我放置了三个带有 1、2 和 3 的 console.log,显示了我希望代码部分运行的顺序。当代码运行并找到查询时,输出是这样的:
I am ready!
string +
2
3
1
这表明代码以错误的顺序运行。
非常感谢所有帮助:)
*更新!非常感谢大家理解为什么它不起作用。我找到了一个解决方案,在 vidid = youtubetest.respond(query, msg) 的主文件中,在函数完成之前不会分配变量,因此它会进入我的代码的其余部分没有变量。为了解决这个问题,我只需放置一个 if 语句检查变量是否未定义并等待它被定义。*
【问题讨论】:
-
您正在编写异步代码。 console.log 2 在异步函数之外。我不确定你会发生什么。
-
对不起,我还没有做过很多类似的事情,我还是个青少年,还在学习 Javascript。你到底是什么意思异步,哪些部分是和不是?
-
this.youtube.search可能是一个异步函数,这意味着它在后台执行某些操作,而函数的 callback 之外的其他代码继续执行。所以你的function(error, result) { ... }是只在搜索操作完成后执行 的回调。因此console.log(2)自然会在回调之前被调用。 -
但是第一个文件中的
console.log(3)是先运行的,所以函数youtubetest.respond(query, msg)不应该在console.log(3)之前运行吗? -
youtubetest.respond可能也是异步的。
标签: javascript node.js scope youtube-data-api discord