Javascript Asynchronous

Handling errors

To handle errors within our callbacks, the following code introduces two callbacks: success and failure to handle the success and failure cases respectively:-

Input:- 
    <script>
        function download(url, success, failure) {
            setTimeout(() => {
                console.log(`Downloading ${url} ...`);
                let error = url.length === 0 || !url; 
                error ? failure(url) :  success(url);
            }, 3000);
        }

        download('',
            function(image) {
                console.log(`Processing the picture ${picture}`);
            },
            function(image) {
                console.log(`Handling error...`);
            }
        );
	  </script> 

Nesting callbacks and the Pyramid of Doom

To download mutiple pictures and process them sequentially, we use a typical approach is to call the download() function inside the callback function in the following example:-

Input:- 
    <script>
        function download(url, callback) {
            setTimeout(() => {
                document.write(`Downloading ${url} ...` + "<br/>");
                callback(url);
            }, 3000);
        }
        const url1 = 'https://www.google.com/pic1.jpg';
        const url2 = 'https://www.google.com/pic2.jpg';
        const url3 = 'https://www.google.com/pic3.jpg';
        download(url1,function(picture){
            document.write(`Processing ${picture}` + "<br/>");
            download(url2,function(picture){
                document.write(`Processing ${picture}` + "<br/>");
                download(url3,function(picture){
                    document.write(`Processing ${picture}` + "<br/>");
                });
            });
        });
	  </script> 

Output:-

However, this callback strategy does not scale well when the complexity grows significantly or we have more images required in our project.

Nesting many asynchronous functions inside callbacks is known as the pyramid of doom or the callback hell. To avoid the pyramid of doom, we use promises or async/await functions.