DEV Community

Discussion on: What dev topic do you think you should understand, but don't?

Collapse
 
3leftturns profile image
Andrew T Johnson

Indeed it does. Functions in a callback chain finish inside to outward. When doing async API calls, I've usually been saving the response (after JSON.parse() ing it) to a global variable like the State in React.

In your example if you want funcWithCallBack to return the results of yetAnotherFuncWithCallback, do you just chain return statements from the inside function to the calling functions?

Like:

funcWithCallback(someVar, () => {
anotherFuncWithCallback(someOtherVar, () => {
yetAnotherFuncWithCallback(aDifferentVar, () => {
return "result";
});
});
});

How do I get result from the innermost function to the top?

Thread Thread
 
wuz profile image
Conlin Durbin

You can make each callback function return the function before it - like this:

const topLevelData = funcWithCallback(someVar, () => {
  return anotherFuncWithCallback(someOtherVar, () => {
    return yetAnotherFuncWithCallback(aDifferentVar, () => {
      return "result";
    });
  });
});

And then those functions would need to return their callback:

function yetAnotherFuncWithCallback(data, callback) {
  doSomethingWithData(data);
  return callback();
}

Then you should have it outside of the callbacks!

Thread Thread
 
3leftturns profile image
Andrew T Johnson

Wow thanks for taking the time to explain that. Much clearer now!