A Guide to Discord Bots
Promises
A promise is the result of an asynchronous function.
The promise will first be pending, and then fulfilled if the function was successful, or rejected if it was not.
If the promise is:
- pending: we cannot get it yet
- fulfilled: we will get it with .then()
- rejected: we will get it with .catch()
Let's take a simple code
client.on('message', message => {
// ...
// In JavaScript '() => {}' is equals to function() {}
// function(m) {} becomes m => {}
message.channel.send('Loading...').then(m => {
// m can be anything you want, but NOT 'message'
// unless you don't plan on using the original message's object
m.edit(`Hey there, ${message.author.tag}.`);
// we edit the 'Loading...' message
console.log(message.content);
// we log the content of the message that triggered this function
}).catch(console.error);
});
channel.send() shows that the returned promised contains a 'Message' object.
This object represents the newly sent message, which contains 'Loading...' in this case.
The code will do the following (in order):
- Send a 'Loading...' message
- If the message was sent:
- Edit the 'Loading...' message to 'Hey there, ' + the original message author's tag + '!'
- Else:
- Print an error
Another example
client.on('message', message => {
// ...
message.react('◀');
message.react('⏹');
message.react('▶');
// Expected result: ◀ ⏹ ▶
// Actual result: a random order
});
Without using promises, the only way you can fix this is by using timers.
Promises are faster, will use less RAM, and have really no downside.
Let's use them:
client.on('message', message => {
// ...
// We are not using the promise's returned object,
// so don't care about the variable's name
message.react('◀').then(e => {
message.react('⏹').then(e => {
message.react('▶');
});
});
// Expected result: ◀ ⏹ ▶
// Actual result: ◀ ⏹ ▶
});
Another example where it's necessary
client.on('message', message => {
// ...
message.guild.fetchMember('user_id').then(member => {
console.log(`Fetched ${member.author.tag}`);
});
// We cannot use the following
// console.log(message.guild.fetchMember(message.author.id));
});