你如何使用 then 回调和 promises
How do you use then call backs and promises
我需要有关承诺和 then
回调的帮助。
我试过阅读指南,但看不懂。
var lastMessage = msg.channel.fetchMessages({ limit: 2 }).then(messages => {
return messages.last();
})
这个returnsPromise { < pending > }
.
.then()
语句不会让程序等待它们完成,它们只是在它们所附加的 Promise 被解析后执行它们的代码。
您可以决定将其余代码移到 .then()
语句中(但它会变得非常混乱)或使用 async/await
.
如果你在一个函数中,你可以声明 async function
: that allows you to use the await
keyword inside it. await
让程序等待 Promise 解决,而不是 Promise 它 returns 你将在 [=11] 中使用的值=]函数。
这是一个例子:
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();
});
});
部分改编自(也是我的)
我需要有关承诺和 then
回调的帮助。
我试过阅读指南,但看不懂。
var lastMessage = msg.channel.fetchMessages({ limit: 2 }).then(messages => {
return messages.last();
})
这个returnsPromise { < pending > }
.
.then()
语句不会让程序等待它们完成,它们只是在它们所附加的 Promise 被解析后执行它们的代码。
您可以决定将其余代码移到 .then()
语句中(但它会变得非常混乱)或使用 async/await
.
如果你在一个函数中,你可以声明 async function
: that allows you to use the await
keyword inside it. await
让程序等待 Promise 解决,而不是 Promise 它 returns 你将在 [=11] 中使用的值=]函数。
这是一个例子:
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();
});
});
部分改编自