Promise object

refer to:

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise

https://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000/0014345008539155e93fc16046d4bb7854943814c4f9dc2000#0

A Promise object is used to represent the final state (completed or failed) of an asynchronous operation, and its return value

1. Grammar

new Promise(function(resolve,reject){  do something    }/* test */)

test is a function with two parameters, resolve and reject. When the Promise constructor is executed, the test function is called immediately. The resolve and reject functions are passed as parameters to test. When the resolve and reject functions are called, the state of the Promise is changed respectively. Either fulfilled or rejected. Some asynchronous operations are usually performed inside the test. Once completed, the resolve function can be called to change the promise state to fulfilled, or change its state to rejected when an error occurs.  

very simple example

let myFirstPromise = new Promise(function(resolve, reject){
    //When the asynchronous code is executed successfully, we will call resolve(...), and when the asynchronous code fails, we will call reject(...)
    //In this example, we use setTimeout(...) to simulate asynchronous code, which may be XHR requests or some API methods of HTML5.
    setTimeout(function(){
        resolve("Success!"); //The code is executed normally!
    }, 250);
});

myFirstPromise.then(function(successMessage){
    //The value of successMessage is the value passed in by calling the resolve(...) method above.
    //successMessage parameter does not have to be a string type, here is just an example
    console.log("Yay! " + successMessage);
});

2. Description

Promise The object is a proxy object (proxies a value), and the proxied value may not be known when the Promise object is created. It allows you to bind separate handlers for the success and failure of asynchronous operations. This allows an asynchronous method to return a value like a synchronous method, but instead of returning the final execution result immediately, a promise object that represents a future result

Promisehas the following states:

  • pending: The initial state, neither a success nor a failure state.
  • fulfilled: means the operation completed successfully.
  • rejected: means the operation failed.

A Promise object in the pending state may trigger the fulfilled state and pass a value to the corresponding state handler, or it may trigger the failed state (rejected) and pass the failure message. When any of these situations occur, the  then handlers of the method binding of the Promise object will be called (then method contains two parameters: onfulfilled and onrejected, both of which are of type Function. When the state of the Promise is fulfilled, Call then's onfulfilled method, when the Promise state is rejected, call then's onrejected method, so there is no competition between the completion of the asynchronous operation and the binding processing method).

Because  Promise.prototype.then and   Promise.prototype.catch methods return promise objects, they can be chained.

With an execute function, we can execute it with a Promise object and get a success or failure result at some point in the future:  

another example

// The ajax function will return a Promise object:
function ajax(method, url, data) {
    var request = new XMLHttpRequest();
    return new Promise(function (resolve, reject) {
        request.onreadystatechange = function () {
            if (request.readyState === 4) {
                if (request.status === 200) {
                    resolve(request.responseText);
                } else {
                    reject(request.status);
                }
            }
        };
        request.open(method, url);
        request.send(data);
    });
}

var log = document.getElementById('test');
var p = ajax('GET', '/api/categories');
p.then(function (text) { // If AJAX succeeds, get the response content
    log.innerText = text;
}).catch(function (status) { // If AJAX fails, get the response code
    log.innerText = 'ERROR: ' + status;
});

Promise can also do more things, for example, there are several asynchronous tasks, you need to do task 1 first, if successful, then do task 2, if any task fails, it will not continue and execute the error handling function.

To execute such asynchronous tasks serially, without Promises, you need to write layers of nested code. With Promises, we simply write:

job1.then(job2).then(job3).catch(handleError);  

E.g:

// Return the calculation result of input*input after 0.5 seconds:
function multiply(input) {
    return new Promise(function (resolve, reject) {
        log('calculating ' + input + ' x ' + input + '...');
        setTimeout(resolve, 500, input * input);
    });
}

// Return the calculation result of input+input after 0.5 seconds:
function add(input) {
    return new Promise(function (resolve, reject) {
        log('calculating ' + input + ' + ' + input + '...');
        setTimeout(resolve, 500, input + input);
    });
}

var p = new Promise(function (resolve, reject) {
    log('start new Promise...');
    resolve(123);
});

p.then(multiply)
 .then(add)
 .then(multiply)
 .then(add)
 .then(function (result) {
    log('Got value: ' + result);
});

3. Method

Promise.all(iterable)

This method returns a new promise object. The promise object will fire when all the promise objects in the iterable parameter object are successful. Once any promise object in the iterable fails, the promise object will fail immediately. After the new promise object triggers the success state, it will use an array containing all promise return values ​​in the iterable as the return value of the success callback, in the same order as the iterable; if the new promise object triggers the failure state, it will The error message of the first failed promise in the iterable will be used as its failure error message. The Promise.all method is often used to handle the state collection of multiple promise objects.

E.g:

var p1 = new Promise(function (resolve, reject) {
    setTimeout(resolve, 500, 'P1');
});
var p2 = new Promise(function (resolve, reject) {
    setTimeout(resolve, 600, 'P2');
});
// Execute both p1 and p2, and execute then after they both complete:
Promise.all([p1, p2]).then(function (results) {
    console.log(results); // get an Array: ['P1', 'P2']
});

Promise.race(iterable)

When any of the child promises in the iterable parameter is successful or failed, the parent promise will immediately call the corresponding handle bound to the parent promise with the success return value or failure details of the child promise as parameters, and return the promise object.  

var p1 = new Promise(function (resolve, reject) {
    setTimeout(resolve, 500, 'P1');
});
var p2 = new Promise(function (resolve, reject) {
    setTimeout(resolve, 600, 'P2');
});
Promise.race([p1, p2]).then(function (result) {
    console.log(result); // 'P1'
});

Promises will get results due p1to faster execution . Execution continues, but the execution result will be discarded.then()'P1'p2

If we combine Promises, we can combine many asynchronous tasks to execute in parallel and serially.

Promise.reject(reason)
Returns a failed Promise object and passes the given failure information to the corresponding processing method
Promise.resolve(value)
Returns a Promise object whose state is determined by the given value. If the value is a Promise object, the object is returned directly; if the value is thenable (that is, an object with a then method), the final state of the returned Promise object is determined by the execution of the then method; otherwise (the value is empty) , a primitive type or an object without a then method), the returned Promise object state is fulfilled, and the value is passed to the corresponding then method. In general, if you don't know if a value is a Promise object, use Promise.resolve(value) to return a Promise object, so that the value can be used as a Promise object.

  

  

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324491303&siteId=291194637
Recommended