Converting callbacks to promises quick and easy
It’s easier to work with Promises (or Async/await) compared to callbacks. This is especially true when you work in Node-based environments. Unfortunately, most Node APIs are written with callbacks.
Today I want to show you how to convert callbacks to promises.
Before you read this article, it helps to know what a promise is.
Converting Node-styled callbacks to promises
Callbacks from Node’s API have the same pattern. They’re passed into functions as the final argument. Here’s an example with fs.readFile
.
Also, each callback contains at least two arguments. The first argument must be an error object.
If you encounter a callback of this pattern, you can convert it into a promise with Node’s util.promisify
.
Once you convert the callback into a promise, you can use it like any other promise.
Once in a while, you may run into APIs that do not conform to Node’s error-first callback format. For these situations, you cannot use util.promisify
. You need to write your own promise.
Writing your own promise
To convert a callback into a promise, you need to return a promise.
You run the code with the callback inside the promise.
If there’s an error, you reject the promise. This allows users to handle errors in catch
.
If there are no errors, you resolve the promise. This allows users to decide what to do next in then
.
Next, you need to provide arguments like filePath
and options
to the code within the promise. To do this, you can use rest and spread operators.
You can then use readFilePromise
as a promise.
Converting non-Node-styled callbacks into promises
Turning a non-Node-style callback into a promise is easy once you know how to construct a promise. You follow the same steps:
- Reject if there’s an error
- Resolve otherwise
Let’s say you have an API that returns data
as the first argument and err
as the second argument. Here’s what you do:
Callbacks with multiple arguments
Let’s say you have a callback with three arguments:
- An error object
- Some data
- Another piece of data
You cannot write this:
The code above doesn’t work because promises can only return one argument. If you want to return many arguments, you can either use an array or an object.
Then, You can destructure the array or object in the then
call.
If you enjoyed this article, please tell a friend about it! Share it on Twitter. If you spot a typo, I’d appreciate if you can correct it on GitHub. Thank you!
Comments
Post a Comment