What is Promise, how to understand Promise? and usage scenarios. .

1. What is Promise

        Promise is a new solution to asynchronous solution in Es6, which is translated as promise. Before Promise appeared, the data returned by the interface we obtained was returned through the callback function. The consequence of this is that when we later project When it is relatively large, it will cause code blockage, which is difficult to understand, bloated, and difficult to maintain. Slowly it will cause the emergence of callback hell.

The so-called callback hell:

doSomething(function(result) {

    doSomethingElse(result, function(newResult) {

      doThirdThing(newResult, function(finalResult) {

        console.log('得到最终结果: ' + finalResult);

      }, failureCallback);

    }, failureCallback);

  }, failureCallback);

 Reading callback hell code is a real headache and unacceptable. . . . .

Promises can now be used to solve this problem

doSomething().then(function(result) {
    return doSomethingElse(result);
  })
  .then(function(newResult) {
    return doThirdThing(newResult);
  })
  .then(function(finalResult) {
    console.log('得到最终结果: ' + finalResult);
  })
  .catch(failureCallback);

    Through the chain call of Promise, I instantly feel the clarity and understandability of the code 

  • Promise chain calls reduce the difficulty of code compilation
  • Significantly enhanced code readability

Promise has three states 

  • in progress
  • resolve successful callback
  • reject callback on failure

features

  • The state of the object is not affected by the outside world, only the result of the asynchronous operation can determine which state it is currently in
  • Once the state changes (from pendingchange to fulfilledand from pendingchange to rejected), it will not change again, and this result can be obtained at any time

2. Usage

        PromiseThe object is a constructor that can declare a variable to create an instance

        

 

PromiseThe constructor accepts a function as a parameter whose two parameters are resolveandreject

  • resolveThe role of the function is to change Promisethe status of the object from "incomplete" to "successful"
  • rejectThe role of the function is to change Promisethe status of the object from "incomplete" to "failed"

PromiseThe constructed instance has the following methods:

  • then() //successful callback
  • catch() //Failed callback
  • finally() //Specify the operation that will be performed regardless of the final state of the Promise object

Guess you like

Origin blog.csdn.net/frelly01/article/details/125811883