【问题标题】:How to wait for reply in an async function before executing .then如何在执行之前等待异步函数中的回复.then
【发布时间】:2021-02-13 03:07:29
【问题描述】:

我正在尝试等待用户在 .then 触发之前选择年龄,但我无法这样做。将函数拆分而不是使用 .then 会更好吗?

谢谢

async function x() {
        await ctx
            .reply(
                'Select your age',
                Markup.keyboard([
                    ['10'],
                    ['11'],
                    ['12'],
                ])
                    .oneTime()
                    .resize()
            )
            .then(() => {
                admin
                    .database()
                    .ref('users/' + ctx.message.chat.id)
                    .set({
                        username: ctx.message.from.first_name,
                        rank: ctx.message.text,
                    });
            });
    }

【问题讨论】:

    标签: node.js async-await telegraf


    【解决方案1】:

    您可以通过异步等待用户重播。

    当用户向您发送请求时,您需要创建不同的反应。

    【讨论】:

      【解决方案2】:

      只有将异步函数与 await 关键字结合使用时,它的优势才会变得明显。 await 仅适用于常规 JavaScript 代码中的异步函数,但它可以单独与 JavaScript 模块一起使用。

      await 可以放在任何基于异步承诺的函数前面,以暂停该行的代码,直到承诺完成,然后返回结果值。

      您可以在调用任何返回 Promise 的函数时使用 await,包括 Web API 函数。

      async function x() {
              let results = await ctx.reply('Select your age',Markup.keyboard([
                          ['10'],
                          ['11'],
                          ['12'],
                      ])
                          .oneTime()
                          .resize()
                  );
                 if (results) {
                    admin
                          .database()
                          .ref('users/' + ctx.message.chat.id)
                          .set({
                              username: ctx.message.from.first_name,
                              rank: ctx.message.text,
                          });
      
                 }
                 else {
                   // log error or throw error
                   }
          }
      
      

      您可以查看link 以获取更多详细信息,了解如何将 Promise 与 async/await 一起使用

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-12-30
        • 1970-01-01
        • 2020-11-18
        • 1970-01-01
        • 2021-03-24
        • 2019-07-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多