ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Promise
    JavaScript 2021. 12. 13. 07:28

    자바스크립트의 Promise 사용법과 문법을 정리하였습니다.



    < Introduction >

    An asynchronous operation is one that allows the computer to “move on” to other tasks while waiting for the asynchronous operation to complete.
    Asynchronous programming means that time-consuming operations don’t have to bring everything else in our programs to a halt.

     

    Example : Operations like making a network request or querying a database can be time-consuming, but JavaScript allows us to execute other tasks while awaiting their completion.

     

     


    < What is a Promise? >

    Promise is object that represents the eventual outcome of an asynchronous operation.

    "I promise to get back to you with the answer as soon as I can," hence the name "promise."

     

    < Promise can be one of three states : >
    1. Pending :
    The initial state— the operation has not completed yet.
    2. Fullfilled(settled) :
    The operation has completed successfully and the promise now has a resolved value.
    3. Rejected(settled) :
    The operation has failed and the promise has a reason for the failure. 
    : We refer to a promise as settled if it is no longer pending— it is either fulfilled or rejected.

    : All promises eventually settle, enabling us to write logic for what to do if the promise fulfills or if it rejects.

     

    Example : DishWasher

    &amp;amp;amp;lt; Promise Example &amp;amp;amp;gt;

    • Pending: The dishwasher is running but has not completed the washing cycle.
    • Fulfilled: The dishwasher has completed the washing cycle and is full of clean dishes.
    • Rejected: The dishwasher encountered a problem (it didn’t receive soap!) and returns unclean dishes.

    If our dishwashing promise is fulfilled, we’ll be able to perform related tasks, such as unloading the clean dishes from the dishwasher. If it’s rejected, we can take alternate steps, such as running it again with soap or washing the dishes by hand.

     

     


    < Constructing a Promise Object >

    const executorFunction = (resolve, reject) => { };
    const myFirstPromise = new Promise(executorFunction);

    1. To create a new Promise object

    • We use the new keyword and the Promise constructor method.
    • The Promise constructor method takes a function parameter called the executor function which runs automatically when the constructor(Promise) is called.

    2. Executor Function : The executor function has two function parameters, resolve( ) and reject( ) functions.

    • resolve( ) is a function with one argument. Under the hood, if invoked, resolve() will change the promise’s status from pending to fulfilled, and the promise’s resolved value will be set to the argument passed into resolve().
    • reject( ) is a function that takes a reason or error as an argument. Under the hood, if invoked, reject() will change the promise’s status from pending to rejected, and the promise’s rejection reason will be set to the argument passed into reject().

     

    Example)

    const executorFunction = (resolve, reject) => {
      if (someCondition) {
          resolve('I resolved!');
      } else {
          reject('I rejected!'); 
      }
    }
    const myFirstPromise = new Promise(executorFunction);

     

    Note : The resolve() and reject() functions aren’t defined by the programmer. When the Promise constructor runs, JavaScript will pass its own resolve() and reject() functions into the executor function.

     

     


    < Consuming Promises >

    How do we tell the computer what should happen then? Promise objects come with an aptly named .then( )
    method. It allows us to say, “I have a promise, when it settles, then here’s what I want to happen…”

     

    Example : DishWasher

    &amp;amp;amp;lt; Promise then &amp;amp;amp;gt;

    In the case of our dishwasher promise, the dishwasher will run then:

    • If our promise rejects, this means we have dirty dishes, and we’ll add soap and run the dishwasher again.
    • If our promise fulfills, this means we have clean dishes, and we’ll put the dishes away.

     

     


    < Consuming Promises : .then() >

    To handle a “resolved” promise, or a "rejected" promise, invoke .then( ) on the promise.


    promise.then(successHandler, failureHandler);

    1. .then( ) is a higher-order function— it takes two callback functions as arguments. We refer to these callbacks as handlers. When the promise settles, the appropriate handler will be invoked with that settled value.

    • The first handler, sometimes called onFulfilled, is a success handler, and it should contain the logic for the promise resolving.
    • The second handler, sometimes called onRejected, is a failure handler, and it should contain the logic for the promise rejecting.

    2. We can invoke .then( ) with one, both, or neither handler! But if the appropriate handler is not provided, instead of throwing an error, .then() will just return a promise with the same settled value as the promise it was called on.

     

    3. .then( ) always return a promise


     

    Example)

    // Example1 : contain only resolved logic
    const prom = new Promise((resolve, reject) => {
      resolve('Yay!');
    });
     
    const handleSuccess = (resolvedValue) => {
      console.log(resolvedValue);
    };
     
    prom.then(handleSuccess); // Prints: 'Yay!'
    
    // Example2 : contain both logic
    let prom = new Promise((resolve, reject) => {
      let num = Math.random();
      if (num < .5 ){
        resolve('Yay!');
      } else {
        reject('Ohhh noooo!');
      }
    });
     
    const handleSuccess = (resolvedValue) => {
      console.log(resolvedValue);
    };
     
    const handleFailure = (rejectionReason) => {
      console.log(rejectionReason);
    };
     
    prom.then(handleSuccess, handleFailure);

     

     


    < Using catch() with Promises >

    To write cleaner code following a principle 'Separation of concerns' using catch( ) method.

     

    • The .catch( ) function takes only one argument : Failure handler function.
      In the case of a rejected promise, this failure handler will be invoked with the reason for rejection.

     

    Example)

    // don't use catch()
    prom
      .then((resolvedValue) => {
        console.log(resolvedValue);
      })
      .then(null, (rejectionReason) => {
        console.log(rejectionReason);
      });
     
    // use catch()
    prom
      .then((resolvedValue) => {
      console.log(resolvedValue);
      })
      .catch((rejectionReason) => {
      console.log(rejectionReason);
      });

     

     


    < Chaining Multiple Promises >

    To execute multiple promises operations in a certain order.
    This process of chaining promises together is called composition. Promises are designed with composition in mind!


    To work properly, must use return.

     

    Example)

    firstPromiseFunction()
    .then((firstResolveVal) => {
      return secondPromiseFunction(firstResolveVal);
    })
    .then((secondResolveVal) => {
      console.log(secondResolveVal);
    });

    : we had to return the promise secondPromiseFunction(firstResolveVal). This ensured that the return value of the first .then() was our second promise rather than the default return of a new promise with the same settled value as the initial.

     

     


    < Using Promise.all() >

    To deal with multiple promises, but don't care about the order : multiple asynchronous operations happening together.

     

    < Promise.all( ) >
    1. Accepts an array of promises as argument.
    2. returns a single promise.
    • If every promise in the argument array resolves, the single promise returned from Promise.all() will resolve with an array containing the resolve value from each promise in the argument array.
    • If any promise from the argument array rejects, the single promise returned from Promise.all() will immediately reject with the reason that promise rejected.

     

    Example)

    let myPromises = Promise.all([returnsPromOne(), returnsPromTwo(), returnsPromThree()]);
     
    myPromises
      .then((arrayOfValues) => {
        console.log(arrayOfValues);
      })
      .catch((rejectionReason) => {
        console.log(rejectionReason);
      });

     

     

    Good Reference Material :

    1. Asynchronous Programming with Promises

     

    Graceful asynchronous programming with Promises - Learn web development | MDN

    Promises are a comparatively new feature of the JavaScript language that allow you to defer further actions until after a previous action has completed, or respond to its failure. This is useful for setting up a sequence of async operations to work correct

    developer.mozilla.org

    2. JavaScript Promises for Dummies

     

    Understanding JavaScript Promises | DigitalOcean

    Get to know JavaScript Promises better.

    www.digitalocean.com

    'JavaScript' 카테고리의 다른 글

    Requests 1  (0) 2021.12.13
    Async Await  (0) 2021.12.13
    Asynchronous / Event Loop  (0) 2021.12.12
    Error Handling  (0) 2021.12.11
    Modules  (0) 2021.12.11

    댓글

Designed by Tistory.