Я использую Discord. js и я не знаю, как получить выгоду от обещания. Вот некоторый контекст:
///File: commands/mail.js///
module.exports = {
name: 'mail',
description: 'A system of collecting, sending, and receiving mail',
async execute(client,message, args) {
const fs = require('fs');
...
...
switch(args[0]){
...
case "check":
...
var name;
var val;
/* [object Promise]--> */ var out = client.users.fetch(recipient.senders[i]);
client.users.fetch(recipient.senders[i]).then((name)=>{
console.log("name.username(inside): "+name.username);
val = name.username;
return (name);
});
console.log("name(outside): ",name);
console.log("out: ",out);
console.log("out.username: ",out.username);
console.log("val: ",val);
/* next line will get an error saying name.username is undefined */
//console.log("name.username(outside): "+name.username);
...
, и я получаю результат:
name(outside): undefined
out: Promise {
User {
id: '1456051390970320640',
bot: false,
username: 'Sir_Ross',
discriminator: '3871',
avatar: 'a956037b05108e4971b93f3ffde97b6c',
lastMessageID: '739552900342349856',
lastMessageChannelID: '739150130339340342',
flags: UserFlags { bitfield: 0 }
}
}
val: undefined
out.username: undefined
name.username(inside): Sir_Ross
Моя проблема в том, что я, очевидно, могу получить свое имя пользователя и распечатать его на консоли, но я не могу получить это из обещания. Как мне получить значение из обещания, чтобы использовать его в другом месте?
Полный код:
module.exports = {
name: 'mail',
description: 'A system of collecting, sending, and receiving mail',
async execute(client,message, args) {
const fs = require('fs');
var path;
if(!args.length){
//No Arguments
return 0;
}
switch(args[0]){
case "send":
// Send Mail
if(args.length<3){
message.reply('Invalid Arguments: !mail send <recipient_id> <message>');
}else{
letter = "";
spaces = 0;
for(i = 0; i<message.content.length;i++){
if(spaces<3){
if(message.content[i]===' '){
spaces++;
}
continue;
}else{
letter+=message.content[i];
}
}
const fs = require('fs');
path = 'mail/';
path+=args[1].substring(3,21);
sender = message.author.id;
path+='.json';
console.log(path);
if(!fs.existsSync(path)){
user = {
user_id: args[1].substring(3,21),
//username: message.author.username,
mailbox: [letter],
senders: [sender],
//status: { 0 },
status: ['0'],
};
data = JSON.stringify(user);
fs.writeFileSync(path,data);
}else{
var recipient;
fs.readFile(path,(err,data) =>{
if(err) throw err;
recipient=JSON.parse(data);
//console.log(recipient);
recipient.mailbox.push(letter);
recipient.senders.push(message.author.id);
recipient.status.push('0');
console.log(recipient);
fs.writeFileSync(path,JSON.stringify(recipient));
});
}
}
break;
case "check":
// Check Inbox
const fs = require('fs');
path = 'mail/';
path+=message.author.id;
// sender = message.author.id;
path+='.json';
if(!fs.existsSync(path)){
message.reply("Mailbox does not yet exist! You need to receive mail first!");
return;
//break;
}else{
var recipient;
fs.readFile(path,(err,data) =>{
if(err) throw err;
recipient=JSON.parse(data);
if(!recipient.senders.length){
message.reply("Mailbox is empty!");
return;
//break;
}else{
outText = "";
for(i = 0; i<recipient.senders.length;i++){
if(recipient.status[i]==='0')outText+="**";
outText+=i+1;
outText+=". ";
//console.log("Promise: ",client.users.fetch(recipient.senders[i]));
var name;
var val;
var out = client.users.fetch(recipient.senders[i]);
client.users.fetch(recipient.senders[i]).then((name)=>{
console.log("name.username(inside): "+name.username);
val = name.username;
return (name);
});
console.log("name(outside): ",name);
console.log("out: ",out);
console.log("out.username: ",out.username);
console.log("val: ",val);
/* name.username is undefined */
//console.log("name.username(outside): "+name.username);
// esc = returnVal();
outText+=val;
if(recipient.status[i]==='0')outText+="**";
outText+='\n';
}
message.reply(outText);
}
});
}
break;
case "read":
// Read Mail
break;
case "delete":
// Delete Mail
break;
case "markRead":
// Mark a Message as Read
break;
case "markUnread":
// Mark a Message as Unread
break;
case "forward":
// Forward a message
break;
}
},
};