ES6 was a success

1. Common syntax for asynchronous operations

  • Event monitoring and response
  • recall

Asynchronous operations of js in the browser are mainly events (Onload, Ready ...), and callbacks are mainly indicated in Ajax requests and in the file API. The problem was not serious at the time. With Node.js, however, the dependency on asynchronicity has increased ... Since non-blocking and high parallelism is the trademark of Node.js and the achievement of non-blocking and high parallelism depends on asynchronous processes; Node. Many of the operations in js are based on system functions, so callback functions are required for subsequent operations.

2. Asynchronous recall problem

 

  • Return and Throw cannot be used normally
  • Batch information cannot be obtained normally
  • It is difficult to establish a connection between multiple callbacks

3. What is promise?

  • In terms of use
    • Mainly used for asynchronous calculations.
    • You can queue asynchronous operations, perform them in the order you expect, and return results that are what you expect.
    • Promises can be passed between objects and edited to make it easier to deal with queues.

4.Promise introduction

Promise is a proxy object. It has nothing to do with the original surgery. We're just adding the original operation to the executor by introducing a callback to avoid further callbacks.

5. Promise 3 conditions

  • outstanding [outstanding] initial state
  • Fulfills
  • rejected [Rejected] Operation failed

When the promise status changes, the response function in .then () is triggered to process the steps below. Once the promise status changes, it doesn't change anymore.

6. Simple example

7. .then ()

  • .then () accepts two functions as parameters that represent satisfied and rejected
  • .then () returns a new Promise instance so it can be chained
  • When the previous promise status changes, .then (), in response to the function execution, selects a specific status according to its final status
  • Status response functions can return new promises or other values
  • When a new promise is returned, the next level.then () is executed after the new promise status changes
  • If any other value is returned, the next level is executed immediately. Then ()
  • eg:
    •