In the Promises, promises post (the last one I did), I said I would probably look at async/await here, so that’s what I’m going to do.

Sometimes, you have a situation where a bunch of nested code blocks can make things confusing.

Sometimes, you want to reference something directly. This is done using async and await. Rather than having to use an asynchronous block (like the .then statements mentioned in the previous post), you can have your code wait for a result using the await keyword. To use our previous example, it could also be written as:

function makePromise(value) {
    return new Promise((resolve, reject)=>{
        if(value !== "hello") reject(`Value ${value} is invalid`);
        resolve(value);
    });
}

async function doIt() {
    let value = await makePromise(value);
    value = value + ", promises!";
    console.log(value);
}

doIt();

This would output the same as the second listing in the previous post. Obviously, there’s a little bit I’ve not said here, and that is that code that needs to be awaited, needs to be in an async block (hence the function on line 8 is marked with the async keyword).

It is also worth noting that (to my knowledge) promises have the option to be called asynchronously, and awaited; as well as all async functions actually return a promise, so can be used in the same way (with multiple .then calls, .catch, and .finally statements all being usable). If you want to do a catch within an async function, just use try...catch as you normally would (I may explain that in my next blog post, to make it clearer to those who may not know what I mean).