A Guide to Discord Bots

Async/Await

Synchronous Functions

Even though JavaScript can be called an asynchronous language, the code will be read from top to bottom like any other language.
If you're calling a function to define or update a variable, the code will usually wait for it to end (let data = getData()). This is the case if you didn't define your function as "Async" or "Asynchronous".

Now, if using an "Async" or "Asynchronous" function, it will not wait for it to end; the code above will most likely return null or a default value (could be an empty string for example).
In this case, the function will return a promise, and you will have to get this promise to set or update your variable).

Asynchronous Functions

Let's say you have an asynchronous method, but you need a way to make it somehow synchronous.
That's where async/await comes to help (Node 8.0.0 and above only)!

  • async: used before a function like this async function foo() {}
  • await: used in async/asynchronous functions to wait for an operation to end before continuing

An example of where and when to use it:

case 'userlist': {
    // same as: async function getData() { }
    let getData = async () => {
        let data = '';

        for (let userid in userlist) {
            // Wait until the promise is fulfilled or rejected
            // client.fetchUser IS asynchronous
            await client.fetchUser(userid).then(user => {
                data += user.tag + '\n';
            });
        }

        return data;
    };

    // call our function
    // without this, it won't get executed
    // because it would never be called
    getData().then(data => console.log(data));
    break;
}

Why do we use .then()? Well, the answer is in Promises!

Short answer: asynchronous functions return a promise when they are done, and using let data = getData() would return a pending promise, not a fulfilled one (which we want to use).
Not using an asynchronous function here would return an empty string, because it wouldn't wait for the 'for' loop to end, thus immediately return the value of 'data', which is empty.

results matching ""

    No results matching ""