DEV Community

Ranjith srt
Ranjith srt

Posted on

js - Promise

Promise

A promise will either resolve with a value or reject with an error.

Syntax:


let promise = new Promise((resolve, reject)=>{

    If(true) {

        resolve();

    }else{

        reject();     
    } 

    });


Enter fullscreen mode Exit fullscreen mode

let promise = new Promise((resolve, reject) => {

  let data = 5;

  //let data = '5';

  if (typeof data === "number") {

    resolve("Success");

  } else {

    reject("Failed");

  }
});

promise

  .then((result) => {
    console.log(`on resolve: ${result}`);
  })
  .catch((error) => {
    console.log(`on reject: ${error}`);
  });  

Enter fullscreen mode Exit fullscreen mode

Function:


function fetchData() {

  return new Promise((resolve, reject) => {
    console.log("Fetching data.. ");

    setTimeout(() => {

      const data = { id: 1, name: "John Doe" };

      const randomVa1ue = Math.random();

      console.log(`Random Value ${randomVa1ue}`);

      const success = randomVa1ue > 0.2;

      if (success) {

        resolve(data);
      } else {

        reject("Fai1ed to fetch data");

      }
    }, 2000);
  });
}

fetchData()

  .then((result) => {
    console.log(`Data fetched: ${result}`);
  })
  .catch((error) => {
    console.log(`Error: ${error}`);
  });


Enter fullscreen mode Exit fullscreen mode

promise1 = new Promise((resolve) => {

    setTimeout(() => {

        resolve('Promise 1 Resloved');

    }, 2000);
});

let promise2 = new Promise((resolve) => {

    setTimeout(() => {

        resolve('Promise 2 Resloved');

    }, 1000);
});

let promise3 = new Promise((resolve) => {

    setTimeout(() => {

        resolve('Promise 3 Resloved');

    }, 3000);

});


//code repetation

promise1.then((result) => {

    console.log(result);
});

promise2.then((result) => {

    console.log(result);
});

promise3.then((result) => {

    console.log(result);
});


Enter fullscreen mode Exit fullscreen mode

// Using Promise.all to call all promises together


Promise.all([promise1, promise2, promise3])

    .then((result) => {

        console.log('All Promise resolved', result);

    })

    .catch((error) => {

        console.log(error);

    });


// Using Promise.race to return as soon as the first promise completes



//2s.       1s.       3s delay 
Promise.race([promisel, promise2, promise3])

    .then((result) => {

        console.log('All Promise resolved', result);

    })

    .catch((error) => {

        console.log(error);
    });

Enter fullscreen mode Exit fullscreen mode

let promise = new Promise(function (resolve, reject) {

    resolve("Process is Successfull");

    // resolve("Sorry some error occured!!!!");

});

`promise`

promise

    .then((value) => {

        console.log(value);

    })

    .catch((error) => {

        console.log(error);

    });


Enter fullscreen mode Exit fullscreen mode

`async & wait  ES6+`


let getData = async () => {

    try {

        let data = await promise;
        console.log(data);
    }
    catch (error) {
        console.log(err);
    }

};

getData();

Enter fullscreen mode Exit fullscreen mode

Top comments (0)