Asynchronous JavaScript

Callback Functions:

Callback functions are functions that are passed as arguments to another function and are executed later, usually after some asynchronous operation.

                                      
                                        function fetchData(callback) {
                                          setTimeout(function() {
                                              const data = 'Hello, World!';
                                              callback(data);
                                          }, 1000);
                                      }
                                      
                                      function processResult(result) {
                                          console.log('Processed:', result);
                                      }
                                      
                                      fetchData(processResult);                                                                                                                                                                                                                             
                                      
                                    

In this example, fetchData simulates an asynchronous operation (e.g., fetching data from a server) and uses a callback function (processResult) to handle the result.


Promises:

Promises provide a cleaner way to handle asynchronous code. A promise represents a value that might be available now, or in the future, or never.

                                      
                                        function fetchData() {
                                          return new Promise(function(resolve, reject) {
                                              setTimeout(function() {
                                                  const data = 'Hello, World!';
                                                  resolve(data); // Fulfill the promise with the data
                                              }, 1000);
                                          });
                                      }
                                      
                                      fetchData()
                                          .then(function(result) {
                                              console.log('Resolved:', result);
                                          })
                                          .catch(function(error) {
                                              console.error('Error:', error);
                                          });                                                                                                                                                                                                                                                                   
                                      
                                    

In this example, fetchData returns a promise. The then method is used to handle the resolved value, and the catch method is used to handle errors.


Async/Await:

The async/await syntax simplifies working with promises and makes asynchronous code look more like synchronous code.

                                      
                                        async function fetchData() {
                                          return new Promise(function(resolve, reject) {
                                              setTimeout(function() {
                                                  const data = 'Hello, World!';
                                                  resolve(data);
                                              }, 1000);
                                          });
                                      }
                                      
                                      async function fetchDataAndProcess() {
                                          try {
                                              const result = await fetchData();
                                              console.log('Resolved:', result);
                                          } catch (error) {
                                              console.error('Error:', error);
                                          }
                                      }
                                      
                                      fetchDataAndProcess();                                                                                                                                                                                 
                                      
                                    

In this example, fetchData returns a promise, and fetchDataAndProcess uses the await keyword to wait for the promise to resolve. The try/catch block handles both successful resolution and errors.


Handling Multiple Promises:

                                      
                                        function fetchData(id) {
                                          return new Promise(function(resolve, reject) {
                                              setTimeout(function() {
                                                  const data = 'Data for ID ' + id;
                                                  resolve(data);
                                              }, 1000);
                                          });
                                      }
                                      
                                      // Using Promise.all to handle multiple promises
                                      const promises = [fetchData(1), fetchData(2), fetchData(3)];
                                      
                                      Promise.all(promises)
                                          .then(function(results) {
                                              console.log('All resolved:', results);
                                          })
                                          .catch(function(error) {
                                              console.error('Error:', error);
                                          });                                                                                                                                     
                                      
                                    

Here, Promise. all is used to wait for each of the promises inside the array to be fulfilled. In practice the then method takes an array of results.

Hey there! Let's go for Learn fasta then! It is more than just coding; it is to have the superpower that can solve any problem. Through simple and easy-to-grasp examples you will sail through the learning process. In addition, it is not just about coding– you will acquire competencies on how to solve complex problems, analyze data, and come up with efficient solutions. Shall we start this wonderful journey together! learnfasta.com terms of use, Copyright 2025 All Rights Reserved.