Skip to content
Advertisement

Returning result from asynchronous function using callbacks

I have to write the body of a function getABC() which essentially has to take in responses from 3 different functions, getA()(synchronous),getB(callback)(callback driven),getC() (promise based). Ultimately I have to return a promise aggregating each function’s result, like [(result of getA),(result of getB),(result of getC)].

I am pasting the snippet of the code down below:

JavaScript

` I cannot edit any other part of the code excluding the getABC() function call. I cannot wrap my head around this problem. Any help would be much appreciated. Thanks in advance!

Advertisement

Answer

Like so:

JavaScript

The result from getA is returned immediately. getC returns a promise, so just await its result. Then call getB and resolve the promise in the callback.

Another option is to make getABC an async function as well. Note the difference in the way getB is called here.

JavaScript

The getB line can be further simplified using a technique called eta reduction. The same technique can be used for the .then(res => console.log(res)) line.

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement