Resolving An Outer Promise Inside A Callback Function In NodeJS (TypeScript/Javascript)

Async-Await along with Promises are often used in NodeJS in order to escape the “Callback Hell Scenario” and to make the code more elegant as well as manageable. However, while development you might come across an npm package that does not support Async/Await and Promises, but rather has Functions that provide their output only as callbacks!

As an example, let’s assume that there is a package with a function that Adds two numbers (just for simplicity), and provides the result in a callback.

The Normal Way When There Are No Callback Involved

The following represents a promise resolution when no callbacks are involved.

The Scenarios Where Normal Way Fails

Here `Promise.resolve(m)` resolves the callback function and not the outer one.

Callback.PNG

As it can be seen from this screenshot too, that VSCode has identified an error with the code.Because there is no return of resolution provided for the Promise of Function doSomething2.

The Solution

1. Resolution After Returning the Required Value from Callback

Resolving in Callback Style

If the above method fails due to some reasons another solution is to resolve the Promise itself in a callback style !

One thought on “Resolving An Outer Promise Inside A Callback Function In NodeJS (TypeScript/Javascript)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s