Understanding of promise

Promise is a new solution to asynchronous programming in js (the old one is pure callback prompt).
What are the specifics:
1. Syntactically, promise is a constructor
2. Functionally, the promise object is used to encapsulate an asynchronous operation and can get it As a result
, the status of the Promise changes from
pengding to resolved. Successful
pending becomes rejected. It
means that there are only these two and a promise object can only be changed once.
Whether it becomes a success or a failure, there will be a result data. The result data of
success will generally become value. The result data is generally called reason

**** callback Hell
plurality of asynchronous operation a series of nested function a
callback hell disadvantage constant read / exception handling unchanged
solution Hell callback

  1.   使用promise的链式  可以有异常传透  阅读方便
    
  2.   async/await****
    

The state of the object is not affected by the outside world. The Promise object represents an asynchronous operation and has three states: pending (in progress), fulfilled/resolved (successful), and rejected (failed). Only the result of the asynchronous operation can determine the current state, and no other operation can change this state.
Once the state changes, it will not change again, and this result can be obtained at any time. There are only two possibilities for the state of the Promise object to change: from pending to fulfilled and from pending to rejected. As long as these two situations occur, the state will be frozen and will not change anymore, and this result will always be maintained. At this time, it is called resolved (finalized). If the change has occurred, and you add a callback function to the Promise object, you will get this result immediately.
Advantages of Promise:
Asynchronous operations can be expressed in a synchronous operation process, avoiding nested callback functions.

const promise = new Promise((resolve,reject)=>{
    
    
//此处执行一些异步操作(调用后台API,定时器等)
 if(/*异步操作成功*/){
    
    
     resolve(value);
 }else{
    
    
     reject(error)
 }
}) 
//其中两个函数的参数值分别为成功和失败后想要传递的结果

Guess you like

Origin blog.csdn.net/wzwzwz555/article/details/109339164