Monday, May 13, 2019

JavaScript(15)---Promise

Promises

Promises are objects that represent the eventual outcome of an asynchronous operation. A Promise object can be in one of three states:
  • Pending: The initial state— the operation has not completed yet.
  • Fulfilled: The operation has completed successfully and the promise now has a resolved value. For example, a request’s promise might resolve with a JSON object as its value.
  • Rejected: The operation has failed and the promise has a reason for the failure. This reason is usually an Error of some kind.
EXAMPLES:
Let’s think of a dishwasher as having the states of a promise:
  • 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.
  1. constructor method 
The Promise constructor method takes a function parameter called the executor function which runs automatically when the constructor is called. The executor function generally starts an asynchronous operation and dictates how the promise should be settled.
  • The executor function has two function parameters, usually referred to as the resolve() and reject() functions.
  • resolve is a function with one argument.
  • reject is a function that takes a reason or error as an argument
.then() is a higher-order function— it takes two callback functions as arguments. We refer to these callbacks as handlers.
  • 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.

To create even more readable code, we can use a different promise function: .catch().
EXAMPLE: 
  1. invoke the checkInventory() function with the order
  2. Add a .then() to the returned promise. Pass in the success handler handleSuccess().
  3. Add a .catch() to the returned promise. Pass in the failure handler handleFailure().
NOTES: process of chaining promises together is called composition.

A combination of the .then() and the .catch() shown below:
And in the terminal, it prints:

Avoiding Common Mistakes

Mistake 1: Nesting promises instead of chaining them.
BEFORE:

checkInventory(order)
    .then((resolvedValueArray) => {
        processPayment(resolvedValueArray)
            .then((resolvedValueArray) => {
                shipOrder(resolvedValueArray)
                    .then((successMessage) => {
                        console.log(successMessage);
                    });
            });
    });

AFTER

checkInventory(order)
.then((resolvedValueArray) => {
  return processPayment(resolvedValueArray);
})
.then((resolvedValueArray) => {
  return shipOrder(resolvedValueArray);
})
.then((successMessage) => {
  console.log(successMessage);
});
To maximize efficiency we should use concurrency, multiple asynchronous operations happening together. With promises, we can do this with the function Promise.all().
Prints:
What I learned today?
  I learned about the codes that will be helpful for opening a new website or a system that could be use in stores to check if things are available and also the deliveries of the shops.
Review:
  • Promises are JavaScript objects that represent the eventual result of an asynchronous operation.
  • Promises can be in one of three states: pending, resolved, or rejected.
  • A promise is settled if it is either resolved or rejected.
  • We construct a promise by using the newkeyword and passing an executor function to the Promise constructor method.
  • setTimeout() is a Node function which delays the execution of a callback function using the event-loop.
  • We use .then() with a success handler callback containing the logic for what should happen if a promise resolves.
  • We use .catch() with a failure handler callback containing the logic for what should happen if a promise rejects.
  • Promise composition enables us to write complex, asynchronous code that’s still readable. We do this by chaining multiple .then()‘s and .catch()‘s.
  • To use promise composition correctly, we have to remember to return promises constructed within a .then().
  • We should chain multiple promises rather than nesting them.
  • To take advantage of concurrency, we can use Promise.all().
What I'll be doing tomorrow?
I will be learning about the ASYNC AWAIT.

No comments:

Post a Comment