ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • The onFulfilled and onRejected Functions
    Study/JavaScript 2020. 5. 15. 19:01

    The onFulfilled and onRejected Functions

    To handle a “successful” promise, or a promise that resolved, we invoke .then() on the promise, passing in a success handler callback function:

     

     

    const prom = new Promise((resolve, reject) => {
      resolve('Yay!');
    });
    
    const handleSuccess = (resolvedValue) => {
      console.log(resolvedValue);
    };
    
    prom.then(handleSuccess); // Prints: 'Yay!'

     

     

    Let’s break down what’s happening in the example code:

    • prom is a promise which will resolve to 'Yay!'.
    • We define a function, handleSuccess(), which prints the argument passed to it.
    • We invoke prom‘s .then() function passing in our handleSuccess() function.
    • Since prom resolves, handleSuccess() is invoked with prom‘s resolved value, 'Yay', so 'Yay' is logged to the console.

    With typical promise consumption, we won’t know whether a promise will resolve or reject, so we’ll need to provide the logic for either case. We can pass both an onFulfilled and onRejected callback to .then().

     

    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);

     

     

    Let’s break down what’s happening in the example code:

    • prom is a promise which will randomly either resolve with 'Yay!'or reject with 'Ohhh noooo!'.
    • We pass two handler functions to .then(). The first will be invoked with 'Yay!' if the promise resolves, and the second will be invoked with 'Ohhh noooo!' if the promise rejects.

    Let’s write some onFulfilled and onRejected functions!

     


    "successful" promise나 해결된 promise를 다루기 위해,

    우리는 success handler 콜백 함수를 전달하면서 promise에 .then() 을 호출한다. 

     

    const prom = new Promise((resolve, reject) => {
      resolve('Yay!');
    });
    
    const handleSuccess = (resolvedValue) => {
      console.log(resolvedValue);
    };
    
    prom.then(handleSuccess); // Prints: 'Yay!'

    예시 코드에서 어떤 일이 일어나고 있는지 설명해보자.

     

    • prom is a promise which will resolve to 'Yay!'.
    • We define a function, handleSuccess(), which prints the argument passed to it.
    • We invoke prom‘s .then() function passing in our handleSuccess() function.
    • Since prom resolves, handleSuccess() is invoked with prom‘s resolved value, 'Yay', so 'Yay' is logged to the console.

    전형적인 promise 소비와 함께, 우리는 promise가 해결될지 또는 reject될지 알 수 없기에, 

    그래서 우리는 어느경우든 로직을 제공할 필요가 있을 것이다.

     

    우리는 'onFulfilled'와 'onRejected' 콜백을 모두 .then()에게 전달할 수 있다. 

     

    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);
    • prom is a promise which will randomly either resolve with 'Yay!'or reject with 'Ohhh noooo!'.
    • We pass two handler functions to .then(). The first will be invoked with 'Yay!' if the promise resolves, and the second will be invoked with 'Ohhh noooo!' if the promise rejects.

    Let’s write some onFulfilled and onRejected functions!

     

     

    // library.js

    const inventory = {
        sunglasses: 1900,
        pants: 1088,
        bags: 1344
    };
    
    const checkInventory = (order) => {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                let inStock = order.every(item => inventory[item[0]] >= item[1]);
                if (inStock) {
                    resolve(`Thank you. Your order was successful.`);
                } else {
                    reject(`We're sorry. Your order could not be completed because some items are sold out.`);
                }
            }, 1000);
        })
    };
    
    module.exports = { checkInventory };

     

    //app.js

     

    const {checkInventory} = require('./library.js');
    
    const order = [['sunglasses', 1], ['bags', 2]];
    
    // Write your code below:
    const handleSuccess = (resolvedValue) => {
        console.log(resolvedValue);
    };
    
    const handleFailure = (rejectReason) => {
        console.log(rejectReason);
    };
    
    checkInventory(order)
        .then(handleSuccess, handleFailure);
    
    
    

    'Study > JavaScript' 카테고리의 다른 글

    API  (0) 2020.05.16
    Storage.setItem()  (0) 2020.05.16
    Consuming Promises  (0) 2020.05.15
    The Node setTimeout() Function  (0) 2020.05.15
    Constructing a Promise Object  (0) 2020.05.15

    댓글

Designed by Tistory.