Javascript 返回未定义的值?
所以我有这个代码:Javascript 返回未定义的值?,javascript,discord.js,Javascript,Discord.js,所以我有这个代码: const Discord=require(“Discord.js”); const bot=new Discord.Client(); const rf=require(“选择随机文件”); const token=“{DATA reversed}”; const prefix=“bot:” const dir='./RandomImage' 函数ranIm(){ rf(目录,(错误,文件)=>{ log(`随机文件为:${file}.`) 返回文件; }) } bot
const Discord=require(“Discord.js”);
const bot=new Discord.Client();
const rf=require(“选择随机文件”);
const token=“{DATA reversed}”;
const prefix=“bot:”
const dir='./RandomImage'
函数ranIm(){
rf(目录,(错误,文件)=>{
log(`随机文件为:${file}.`)
返回文件;
})
}
bot.on('ready',()=>{
bot.user.setStatus(“在线”);
bot.user.setActivity('with'+bot.guilds.cache.size+“servers!”);
log(“{BOT initialized}前缀为”+前缀)
})
bot.on(“消息”,msg=>{
let contentDown=msg.content.toLowerCase();
设args=contentDown.substring(前缀.length).split(“”);
if(contentDown.substring(0,prefix.length)==前缀){
开关(参数[0]){
“随机”案例:
console.log(ranIm());
msg.channel.send(“这是您的图像:您的函数ranIm
本身不返回任何内容。返回文件
位于rf
函数的第二个参数内。因此返回文件现在是rf(dir,…)
函数的结果
因此,您需要为ranIm
函数设置一个回调参数,如下所示:
函数ranIm(回调){
rf(目录,(错误,文件)=>{
log(`随机文件为:${file}.`)
回调(文件)
})
}
ranIm(函数(随机文件){
//用随机文件做东西
})
另一个选择是使用
函数ranIm(回调){
返回新承诺((拒绝、解决){
rf(目录,(错误,文件)=>{
如果(错误)拒绝(错误);
解决(文件);
})
})
}
ranIm().then(文件=>{
//用随机文件做东西
})