Sitemap
Brett Schules

Brett Schules

JavaScript Async/Await

2 min readOct 28, 2017

For me personally, I think the Async/Await is of the most overlooked and useful function in Javascript. As the web becomes more reliant on making AJAX calls and the use of promises, Javascript has come a long way since the old days of using the messy XML HttpRequests to then function and now async/await. Let’s take a look at how the Async/Await functions work.

Get Brett Schules’s stories in your inbox

Join Medium for free to get updates from this writer.

Async is used before a function which allows it to alway return a promise.

async function test() {
return "Hello World";
}

test().then(console.log)

Now let’s look at the await operator which makes JavaScript wait until that promise settles and returns its result. Note that the await operator can only be used inside the async function.

function getMessage() {
return new Promise((resolve, reject) => {
setTimeout(() => resolve("Hey"), 2000);
});
}
async function start() {
const message = await getMessage();
console.log(message)
console.log("Hello")
}
start().then(msg => msg);

In the function getMessage(), it creates a promise with the string of “Hey” (we used the setTimout to stimulate the time it may take to return a list of promises). In the start function, we set a variable called message which will return the promise from the getMessage() function. Finally, we console.log our data of (“Hey”) and “Hello”). This returns the following console logs Hey and Hello in order as if the function was synchronous meaning the code was executed in sequential order.

Imagine if we did not use the async and await, then the start() function would executed asynchronously meaning the multiple things are running in the background at once. The getMessage() would be fired first however it will not run until two seconds later(stimulated the promise yet to be resolved), the next line of code is executed. The start function would instead console.log “Hello”, then “Hey” when the getMessage function is finally resolved.

--

--