How to deal with nested callbacks and avoid “callback hell”
JavaScript is a strange language . Once in a while, you have to deal with a callback that’s in another callback that’s in yet another callback. People affectionately call this pattern the callback hell . It kinda looks like this: firstFunction(args, function() { secondFunction(args, function() { thirdFunction(args, function() { // And so on… }); }); }); This is JavaScript for you. It’s mind-boggling to see nested callbacks, but I don’t think it’s a “hell”. The “hell” can be manageable if you know what to do with it. On callbacks I assume you know what callbacks are if you’re reading this article. If you don’t, please read this article for an introduction to callbacks before continuing. There, we talk about what callbacks are and why you use them in JavaScript. Solutions to callback hell There are four solutions to callback hell: Write comments Split functions into smaller functions Using Promises Using Async/await Before we dive in...
Comments
Post a Comment