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:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use currying to return a function that returns a
Promisewhich calls the original function. - Use the rest operator (
...) to pass in all the parameters. - If you are using Node 8+, you can use
util.promisify. - Here's an example code snippet:
const promisify =
(func) =>
(...args) =>
new Promise((resolve, reject) =>
func(...args, (err, result) => (err ? reject(err) : resolve(result)))
);
- To use this function, define the asynchronous function and pass it as a parameter to the
promisifyfunction. 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.