Categories
JavaScript Answers

How to convert an existing callback API to promises with Node.js?

Spread the love

Sometimes, we want to convert an existing callback API to promises with Node.js.

In this article, we’ll look at how to convert an existing callback API to promises with Node.js.

How to convert an existing callback API to promises with Node.js?

To convert an existing callback API to promises with Node.js, we can use the Promise constructor.

For instance, we write

const load = (param) => {
  return new Promise((resolve, reject) => {
    getStuff(param, (err, data) => {
      if (err !== null) {
        reject(err);
      } else {
        resolve(data);
      }
    });
  });
}

to create the load function that returns a promise that we create with the Promise constructor.

If there’s an error, err is set to a value, so we call reject with the err object.

Otherwise, we call resolve with the data that we get when the getStuff function succesfully runs.

Conclusion

To convert an existing callback API to promises with Node.js, we can use the Promise constructor.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *