You are viewing the preview version of this book
Click here for the full version.

Async functions

Normal functions return a result with the return keyword:

const fn = () => {
  return 5;
}

fn();
// 5

Async functions, in contrast, return a Promise:

const asyncFn = async () => {
  return 5;
}

asyncFn();
// Promise

You can make any function async with the async keyword, and there are a lot of functions that return a Promise instead of a result.

For example, to read a file from the filesystem, you can use fs.promises, a variant of the fs functions returning Promises:

const fs = require("fs");

fs.promises.readFile("test.js");
// Promise

Or convert an image to jpeg with the sharp library, which also returns a Promise:

const sharp = require("sharp");

sharp("image.png")
  .jpeg()
  .toFile("image.jpg");
// Promise

Or make a network request with fetch:

fetch("https://advancedweb.hu");
// Promise

How to use the Promise

An async function still has a return value, and the Promise holds this result. To get access to the value, attach a callback using the then() function. This callback will be called with the result of the function.

To get the file contents after the readFile:

const fs = require("fs");

fs.promises.readFile("test.js").then((result) => {
  console.log(result);
  // Buffer
});

Similarly, to get the result of our simple async function, use then():

const asyncFn = async () => {
  return 5;
}

asyncFn().then((res) => {
  console.log(res);
  // 5
});

The benefits of Promises

But why complicate a function call with Promises? A normal function just returns a value that can be used on the next line, without the need for any callbacks.

The benefit of returning a Promise instead of a value is that the result might not be ready by the time the function returns. The callback can be called much later, but the function must return immediately. This extends what a function can do.

// sync
fn();
// result is ready

// async
asyncFn().then(() => {
  // result is ready
})
// result is pending

There is more, but you've reached the end of this preview
Read this and all other chapters in full and get lifetime access to:
  • all future updates
  • full web-based access
  • PDF and Epub versions