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

FULL DISCUSSION
 

Promises vs Callbacks. Mostly I Google my way out of callback hell, or save the stuff I need from API calls straight to the state in React. And I really don't even know what callback hell is, so also 'Callback Hell'. I am proud that I do know that callback hell exists, even though I don't know what it is.

 

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 code. Here is an example of what it looks like:

funcWithCallback(someVar, () => {
   anotherFuncWithCallback(someOtherVar, () => {
       yetAnotherFuncWithCallback(aDifferentVar, () => {
           // ... and on and on.
       });
   });
});

The main difference between callbacks and promises is how the render in the call stack. In that example above, the call stack looks kinda like this:

yetAnotherFuncWithCallback
anotherFuncWithCallback
funcWithCallback

Each function has to finish running before the next one will complete. Each of those is a frame in the call stack.

Promises make functions asynchronous and chainable, which is what happens when you call .then(). A promise tells the browser: "Hey, this function will return at some point in the future. When it does, run this next function that I defined in .then.

Does that make sense?

 

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