我需要有关Promise和then
回调的帮助。
我曾尝试阅读指南,但听不懂。
var lastMessage = msg.channel.fetchMessages({ limit: 2 }).then(messages => {
return messages.last();
})
这将返回Promise { < pending > }
。
答案 0 :(得分:2)
.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(也是我的)