Working with the Async/Await keywords can be confusing at times but becomes easier to use once you understand how they work. In this blog post, I will try to make it easier to understand working with them.
Using the Async
keyword before a function makes it return a Promise. Because JavaScript is synchronous, code execution usually doesn't wait for results unless we use objects like Promises. We know sometimes reading files or API calls can take a while before we have a response and at the same time JavaScript needs to carry on with executing code. Promises bring in the aspect of being asynchronous and tells JavaScript to carry on with code that doesn't have to wait for a result before coming back to the code inside the Promise once it has the results ready.
A Promise here is basically an object that links code which can take some time to be executed to the code which must wait for the previous code's result. Examples where promises are used can be in Timeouts or making API calls & waiting for the response; whether it is a result or an error. An example of how Async
is used is:
async function sayHello() {
return "Hello there!";
}
The above function is the same as doing the following:
function sayHello() {
return Promise.resolve("Hello there!");
}
When working with Async functions/Promises in JavaScript, we can use .then
to get the value they return when we call them:
sayHello().then(
(result) => {
// do something with the value being returned once promise is resolved
console.log(result);
},
(error) => {
// you can log error here if Promise is rejected or is not resolved
console.log(error);
}
);
You've probably seen .then
being used a lot in API calls e.g: using Axios HTTP Client.
You can learn more about Promises here.
This keyword is used inside Async
functions, if you try using the keyword outside Async
functions you will get a syntax error. The purpose of Await
is to make the function execution pause until a Promise is resolved before continuing with the execution. An example would be pausing execution until API call gets a response or pausing until a file/directory is read. In the following code block, the function execution pauses, when Await
is used, until the specified directory is read (in Node.js):
const path = require("path");
const fs = require("fs");
async function checkForFiles() {
var contents = [];
// you can do the code without a try/catch block but you will not be able to handle errors/exceptions such as a specified directory not existing
try {
const pages = await fs.promises.readdir("pages");
for (let file of pages) {
try {
if (path.parse(file).ext === EXTENSION) {
contents.push({ name: path.parse(file).name });
}
} catch (error) {
console.log(error.message);
}
}
return contents;
} catch (error) {
console.log(error);
}
}
We can then call the function and use .then
to get the value it returns once the Promise is resolved:
checkForFiles().then(
(result) => {
for (let i = 0; i < result.length; i++) {
// do something with the contents returned from the function (Promise is resolved)
}
},
(error) => {
console.log(error);
}
);
}
I hope this article has helped you to understand more on Async/Await in JavaScript. If there's anything that wasn't clear or if I have made a mistake, you can let me know in the comments section.