What is promise? What are the status and parameters? how to use?

What is promise?
The promise object is actually a constructor function, which is used to solve asynchronous programming. It is mainly used for asynchronous calculation and solves the problem of callback hell. It is not multiple nesting, but chained calls. Using the .then method is for callback functions. improvement of

What are the three states of promise?
1. Pending initial state
2. Fulfilled operation successful state
3. Rejected operation failed state The state of the
Promise object can only be changed in two ways:
from pending to fulfilled, that is, from the initial state to the successful state,
from pending to rejected, that is, from the initial state The state changes to a failed state
as long as these two situations occur, the state is frozen and will not change anymore. (The state change is irreversible)

What are the parameters of promise?
Promise accepts a function as a parameter, the function has two parameters (resolved, rejected)

The function of the resolve function is to change the state of the Promise object from "unfinished" to "successful" (that is, from pending to resolved), called when the asynchronous operation succeeds, and pass the result of the asynchronous operation as a parameter;
reject The function of the function is to change the state of the Promise object from "unfinished" to "failed" (that is, from pending to rejected), to be called when the asynchronous operation fails, and to pass the error reported by the asynchronous operation as a parameter.
usage:

var promise = new Promise((resolve, reject) => {
    
    /* executor函数 */
    // ... some code
    if (/* 异步操作成功 */){
    
    
        resolve(value);
    } else {
    
    
        reject(error);
    }
});

Guess you like

Origin blog.csdn.net/weixin_53944118/article/details/114920118