【发布时间】:2021-05-26 01:05:16
【问题描述】:
async 函数有问题。
在内部promisethen回调中,值设置正确,但是返回这个变量后,promise解析,调用者总是得到一个空值!
注意:这是针对不和谐机器人的:我尝试使用用户的 ID 获取用户的显示名称。
这里是async 函数:
export async function getUserInfo(userNameLooking: string, guild: Guild): Promise<UserSettings | null> {
console.log("Looking for user", userNameLooking);
userList.forEach(user => {
console.log("Analyzing user ID", user);
let thanos = guild.client.users.fetch(user);
thanos.then(function (result1) {
console.log("... This ID user name is", result1.username);
if (result1.username.toLowerCase() == userNameLooking.toLowerCase()) {
console.log("... Match !");
console.log(cacheUser[user] );
return cacheUser[user] ;
}
else {
console.log("... Not match ...");
}
}, function (){console.log("ERROR : Can't find name of ID", user)});
})
return null;
}
调用上述函数的代码:
var user;
getUserInfo(args.userName, message.guild).then(function (result1) {
console.log("Caller Result :", result1); // <--- always null!
user = result1;
if (user == null) {
return message.channel.send("User is unknown");
}
const embed = new MessageEmbed();
embed.setTitle("NAME: " + user.userId);
});
以及控制台中的输出:
Looking for user totolitoto
Analyzing user ID 752614956918112386
... This ID user name is TotoLitoto
... Match !
{
_id: 60abd6dada6f9ad06fbfb9eb,
userId: '752614956918112386',
userName: 'TotoLitoto',
userLang: 'en'
}
Caller Result : null
有什么问题?
【问题讨论】:
-
您的函数执行
forEach,然后执行return null;。你还期待什么?这是它拥有的单个return语句。 -
但是foreach中有一个返回...没有?
-
是的,但这是 callback 函数的(无用)返回值,而不是您的外部函数。
标签: typescript promise