【问题标题】:How do you use then call backs and promises你如何使用 then 回调和承诺
【发布时间】:2019-02-02 21:47:27
【问题描述】:

我需要有关承诺和then 回调的帮助。
我试过阅读指南,但看不懂。

var lastMessage = msg.channel.fetchMessages({ limit: 2 }).then(messages => {
  return messages.last();
})

这将返回Promise { < pending > }

【问题讨论】:

  • 那么,除了直接“理解”之外,您究竟想用代码实现什么?
  • 您能否添加有关与正在执行的代码相关的任何错误的信息?
  • 我正在尝试将第二条消息的内容存储到一个字符串中

标签: node.js discord.js


【解决方案1】:

.then() 语句不会让程序等待它们完成,它们只是在它们附加到的 Promise 被解析后执行它们的代码。
您可以决定将其余代码移到 .then() 语句中(但它会变得非常混乱)或使用 async/await
如果您在一个函数内部,您可以将其声明为 async function:,这样您就可以在其中使用 await 关键字。 await 使程序等待 Promise 解决,而不是 Promise,它返回您将在 .then() 函数中使用的值。
这是一个例子:

client.on('message', async () => {
  // You can do everything you would normally do here
  // Using the 'async' keyword allows you to later user 'await'
  var lastMessage = await msg.channel.fetchMessages({ limit: 2 }).then(messages => {
    return messages.last();
  });
});

部分改编自this answer(也是我的)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-18
    • 1970-01-01
    • 2016-03-09
    • 2017-12-05
    • 2013-07-22
    • 2013-06-15
    • 2017-12-20
    相关资源
    最近更新 更多