100+ JavaScript

Loop In JS Function localStorage Drag Drop Object get set

Asynchronous JS

Callback Promises

Web API

Web API Intro Cookie Fetch API

JS PDF

Basic Pdf

Toast.js

Basic Toastr

💑Learn About Asynchronous JS Promises🤝

Promises are a fundamental concept in modern JavaScript for handling ansynchronous operations.The provide a cleaner and more manageable way to deal with tasks that take time to complete such as fetching data from server, reading files or complex calculations.

Why uses promises?

  • Avoiding Callback Hell: Promises help manage multiple asynchronous task without creating nested callbacks.
  • Better Error Handling: Promises provide a clear way to handle errors using catch().

Promises has three states:

  • Pending: The initial state, neither fulfilled nor rejected.
  • Fulfilled: The operation completed successfully.
  • Rejected: The operation failed.
Basic declarations:
                            
    const myPromise = new Promise((resolve, reject) => {
        // Asynchronous operation here
        if (/* condition for success */) {
            resolve(value); // Fulfill the promise with a value
        } else {
            reject(error); // Reject the promise with an error
        }
        });
    
    
    myPromise
      .then(value => {
        // Handle successful result
        console.log(value);
      })
      .catch(error => {
        // Handle error
        console.error(error);
      });                
                            
                           

Here is another example

                            
    const myPromises=new Promise((resolve,reject)=>{
    
        setTimeout(()=>{
            const success=true;
            if(success){
                resolve("Data fetched successfully");
            }
            else{
                reject("Error fetching data");
            }
    
        },2000);
    
    });
    
    
    myPromises.then((value)=>{
        console.log(value);
    }).catch((error)=>{
        console.log(error);
    });          
                            
                           

🌐Application🈸

Let's say you want to fetch data from an API(like user details). The process is asynchronous, so you don't know exactly when it will complete.

    
    function fetchData(){
        return new Promise((resolove,reject)=>{
    
            setTimeout(()=>{
                const user={id:1,name:"Shanto"};
                const success=true;
                if(success){
                    resolove(user);
                }
                else{
                    reject("Failed to fetch data!!");
                }
    
            },2000);
    
        });
    }
    
    fetchData().then((user)=>{
        console.log(`User-Id: ${user.id} User-Name: ${user.name}`);
    }).catch((error)=>{
        console.log(error);
        
    });
        
    
    

Promises Chaining⛓️

    
    function walkDog(){
        return new Promise((resolve,reject)=>{
            setTimeout(()=>{
                const walk=true;
                if(walk){
                    resolve("You walk the dog🐕");
                }
                else{
                    reject("you don't walk the dog");
                }
    
            },1500);
        });
    }
    
    
    function cleanKitchen(){
        return new Promise((resolve,reject)=>{
            setTimeout(()=>{
                const clean=true;
                if(clean){
                    resolve("You clean the kitchen👩‍🍳");
                }
                else{
                    reject("You don't clean the kitchen");
                }
    
            },2500);
        });
    }
    
    
    function takeOutTrash(){
        return new Promise((resolve,reject)=>{
            setTimeout(()=>{
                const trash=true;
                if(trash){
                    resolve("You take the trash🗑️");
                }
                else{
                    reject("you don't take the trash");
                }
    
            },1000);
        });
    }
    
    walkDog().then((value)=>{
        console.log(value);
        return cleanKitchen();
    }).then((value)=>{
        console.log(value);
        return takeOutTrash();
    }).then((value)=>{
        console.log(value);
    }).catch((error)=>{
        console.error(error);
    });