re: What dev topic do you think you should understand, but don't? VIEW POST

TOP OF THREAD FULL DISCUSSION
re: Oh hey, I can actually answer this! Callback Hell is pretty simple - it's when you have a bunch of nested callbacks, making difficult to read the c...
 

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?

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!

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

code of conduct - report abuse