Async & Await in JavaScript

In the previous lesson, we were able to create asynchronous programs using promises, which gives us a much easier syntax compared to the traditional callback structure. But remember that our goal is to have something more like this:

javascript
1const variable = asyncFunction(. . .);

Essentially, we want a more synchronous way to write asynchronous programs, and that is what async/await syntax is for. It is a way for us to further simply the promise syntax.

A function marked with async will be asynchronous, meaning it will return a promise. And await is used inside the async function to pause the execution of the function until a promise is resolved. For example, recall that in the last lesson we created a read() function that returns a promise to read a file.

javascript
1function read(filePath) {
2  return new Promise((resolve, reject) => {
3    fs.readFile(filePath, "utf8", (err, data) => {
4      if (err) {
5        reject(err);
6      } else {
7        resolve(data);
8      }
9    });
10  });
11}

And then we used the same promise syntax to create the compareFiles() function.

javascript
1function compareFiles(f1, f2, f3) {
2  return Promise.all([read(f1), read(f2), read(f3)])
3    .then(([data1, data2, data3]) => {
4      if (data1 === data2 && data2 === data3) {
5        console.log("Files are the same.");
6      } else {
7        console.log("Files are not the same.");
8      }
9    })
10    .catch((error) => console.error("Error reading files:", error));
11}
12
13compareFiles("./file1.txt", "./file2.txt", "./file3.txt");

This syntax is a big improvement compared to the old-school callbacks, but async allows us to write this function in a synchronous way:

javascript
1async function compareFiles(f1, f2, f3) {
2  const [data1, data2, data3] = await Promise.all([
3    read(f1),
4    read(f2),
5    read(f3),
6  ]);
7
8  if (data1 === data2 && data2 === data3) {
9    console.log("Files are the same.");
10  } else {
11    console.log("Files are not the same.");
12  }
13}

In this case, the keyword await tells JavaScript to wait for all the promises have been resolved, and the output has been passed to the corresponding variables in the array, and then continue to the next step.

Wait, there is more!

You need an account to access the rest of this lesson. Our course is 50% off for limited time only! Don't miss the opportunity!

🎉 Create an Account 🎉