Asynchronous Functions to Promises

Beginner

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will learn how to convert an asynchronous function to return a promise using the promisify function. This will allow us to write cleaner and more readable code by avoiding callback functions. We will also explore the use of currying and the rest operator in JavaScript.

This is a Guided Lab, which provides step-by-step instructions to help you learn and practice. Follow the instructions carefully to complete each step and gain hands-on experience. Historical data shows that this is a beginner level lab with a 82% completion rate. It has received a 100% positive review rate from learners.

Promisify Function

To convert an asynchronous function to return a promise, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use currying to return a function that returns a Promise which calls the original function.
  3. Use the rest operator (...) to pass in all the parameters.
  4. If you are using Node 8+, you can use util.promisify.
  5. Here's an example code snippet:
const promisify =
  (func) =>
  (...args) =>
    new Promise((resolve, reject) =>
      func(...args, (err, result) => (err ? reject(err) : resolve(result)))
    );
  1. To use this function, define the asynchronous function and pass it as a parameter to the promisify function. The returned function will now return a promise.
const delay = promisify((d, cb) => setTimeout(cb, d));
delay(2000).then(() => console.log("Hi!")); // Promise resolves after 2s

The delay function is an example of an asynchronous function that now returns a promise using the promisify function.

Summary

Congratulations! You have completed the Promisify Function lab. You can practice more labs in LabEx to improve your skills.