NodeJS is a backend runtime environment that runs on the V8 engine and enables us to write and execute server-side JavaScript.
Use promises instead of callbacks
NodeJS was originally built using a callback pattern for asynchronous calls. All of NodeJS’s builtins are structured this way: you provide the main arguments along with a callback function that is applied when the asynchronous operation is done.
Fortunately, it’s quite easy to convert these methods to using promises instead. Let’s look at two different ways.
Using promisify
You can use a utility function, promisify
, from the utils module to wrap the function using a callback in a promise.
It works for all functions that follow the NodeJS callback convention, which means that it works for a range of old third-party libraries for NodeJS as well.
Using module/promises
Instead of handling the promise-wrapping yourself, all NodeJS builtins come with a promisified version of their functions, straight from the module itself. This is, by far, the easiest way to use promises in NodeJS. Please, stick to this pattern anywhere you can.
Async handlers in AWS Lambda
The same goes for AWS Lambda. You don’t have to use the callback
argument anymore. Instead, declare the handler as async
, and return the result instead.
If you need to fulfill promises during the function call, you simply apply the await
keyword like you normally would.