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 . const fs = require ( 'fs' ) fs . readFile ( filePath , options , callback ) Also, each callback contains at least two arguments. The first argument must be an error object. fs . readFile ( 'some-file' , ( err , data ) => { if ( err ) { // Handle error } else { // Do something with data } } ) If you encounter a callback of this pattern, you can convert it into a promise with Node’s util.promisify . const fs = require ( '...