javascript-async-operations-chaining-promise

anonymous·2022년 10월 16일
0

Promise State types

  • pending
  • fulfilled
  • rejected

Example

const count = true;

let countValue = new Promise(function (resolve, reject) {
    if (count) {
        resolve("There is a count value.");
    } else {
        reject("There is no count value");
    }
});
console.log(countValue);
// Promise {<resolved>: "There is a count value."}

Promise Chaining

Handle more than one async. task one after another

Promise Chaining Syntax

api().then(function(result) {
    return api2() ;
}).then(function(result2) {
    return api3();
}).then(function(result3) {
    // do work
}).catch(function(error) {
    //handle any error that may occur before this point 
});

then() syntax

promiseObject.then(onFulfilled, onRejected);

then() example

// returns a promise
let countValue = new Promise(function (resolve, reject) {
  resolve("Promise resolved");
});

// executes when promise is resolved successfully
countValue
  .then(function successValue(result) {
    console.log(result);
  })
  .then(function successValue1() {
    console.log("You can call multiple functions this way.");
  });

catch() example

// returns a promise
let countValue = new Promise(function (resolve, reject) {
   reject('Promise rejected'); 
});
// executes when promise is resolved successfully
countValue.then(
    function successValue(result) {
        console.log(result);
    },
 )
  // executes if there is an error
    .catch(
    function errorValue(result) {
      console.log(result);
    }
  );

REF

RECOMMENDED!
https://www.programiz.com/javascript/promise

profile
기술블로거입니다

0개의 댓글