从函数返回承诺值 [英] Returning promise value from function
问题描述
我试图使该递归函数返回一个promise值,我不知道该怎么做,我尝试过以不同的方式编写它,但是它们都以 search
结尾正在 undefined
I am trying to make this recursive function return a promise value, I don't know how to go about doing it, I have tried writing it in different ways but they all ended up with search
being undefined
public search(message: Message) {
let search: string;
const filter = (msg: Message) => msg.author.id === message.author.id;
message.channel.send('Enter search term').then(msg => {
message.channel.awaitMessages(filter, { max: 1 })
.then(collected => {
if (collected.first()!.content === 'Test') this.search(message);
msg.delete()
collected.first()!.delete()
search = collected.first()!.content
})
})
})
return search; // Variable 'search' is used before being assigned.ts(2454)
}
推荐答案
您是否考虑过使用异步功能?仅此一点就可以使您的代码更易于调试和理解.
Have you considered using an async function? That alone would make your code easier to debug and understand.
public async search(message: Message): Promise<any> {
const filter = (msg: Message) => msg.author.id === message.author.id;
const msg = await message.channel.send('Enter search term');
const collected = await message.channel.awaitMessages(filter, { max: 1 });
if (collected.first()!.content === 'Test') return this.search(message);
msg.delete();
collected.first()!.delete();
const search = collected.first()!.content;
return search;
}
在这里, search
被定义为const并立即返回,这对于编译器来说很好.我没有使用变量来保存嵌套的 this.search
调用的返回值,但是如果您决定在计算实际结果之后执行更多代码,则可能必须这样做.
Here, search
is defined as a const and immediately returned, and that's fine to the compiler.
I didn't use a variable to save the return value of the nested this.search
call, but you may have to if you decide to execute more code after calculating the actual result.
这篇关于从函数返回承诺值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!