从函数返回承诺值

编程入门 行业动态 更新时间:2024-10-23 09:25:57
本文介绍了从函数返回承诺值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图使该递归函数返回一个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.

更多推荐

从函数返回承诺值

本文发布于:2023-10-25 08:16:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1526428.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!