简体   繁体   中英

How do I convert this chained promises code with callback to async/await

How do I convert this chained promises code with callback to async/await

I have no idea on how to go about converting this code to async/await so that its more readable

var responseCallbacks = {};

bot.onText(/\/something/, async (msg) => {
  var callback = responseCallbacks[msg.chat.id];
  if (callback) {
    delete responseCallbacks[msg.chat.id];
    return callback(msg);
  }
  bot.sendMessage(msg.chat.id, "something").then(() => {
    responseCallbacks[msg.chat.id] = (answer) => {
      var something = answer.text;

      bot.sendMessage(msg.chat.id, "something else").then(() => {
        responseCallbacks[msg.chat.id] = (answer) => {
          var somethingElse = answer.text;
          console.log(something, somethingElse);
        };
      });
    };
  });
});

Here is what you want:

var responseCallbacks = {};

bot.onText(/\/something/, async (msg) => {
    var callback = responseCallbacks[msg.chat.id];
    if (callback) {
        delete responseCallbacks[msg.chat.id];
        return callback(msg);
    }

    await bot.sendMessage(msg.chat.id, "something");
    responseCallbacks[msg.chat.id] = async (answer) => {
        var something = answer.text;

        await bot.sendMessage(msg.chat.id, "something else");
        responseCallbacks[msg.chat.id] = (answer) => {
            var somethingElse = answer.text;
            console.log(something, somethingElse);
        };
    };
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM