This is the 21st day of my participation in the August Text Challenge.More challenges in August


What is a Promise

Promises are components that abstract asynchronous processing objects and perform various operations on them. We’ll cover this in more detail later, but promises weren’t invented in JavaScript.

When it comes to javascript-based asynchronous processing, I think most people think of using callback functions.

// Asynchronous processing of callback functions is used
getAsync("fileA.txt".function(error, result){
    if(error){// Obtain the failure of processing
        throw error;
    }
    // How to handle success
});
//<1> The arguments passed to the callback function are (error object, result of execution) combinations
Copy the code

Promises formalize similar asynchronous processing objects and processing rules, and write them in a unified interface. Writing anything other than a prescribed method would be a mistake.

// Here is an example of asynchronous processing using Promise
var promise = getAsyncPromise("fileA.txt"); 
promise.then(function(result){
    // The file content is successfully obtained
}).catch(function(error){
    // Failed to get file contents
});
<1> returns a Promise object
Copy the code

Promise’s ability to easily model complex asynchronous processing is arguably one reason to use promises.

ES6 Promises API

There are not many apis defined in ES6 Promises. There are three types of apis.

Constructor

Promise is similar to XMLHttpRequest in that a new new Promise object is created as an interface from the constructor Promise.

To create a Promise object, instantiate it by calling the Promise constructor with new.

var promise = new Promise(function(resolve, reject) {
    // Asynchronous processing
    // After processing, call resolve or reject
});
Copy the code

Instance Method

The promise.then() instance method can be used for callbacks that are called in resolve(success)/reject(failure) to set the value of a promise object generated by new.

promise.then(onFulfilled, onRejected)
Copy the code
  • Resolve

    Ondepressing will be called

  • Reject (reject

    OnRejected is called

Ondepressing and onRejected are both optional parameters.

Promise. then can be used for both success and failure. In addition, if you only want to handle exceptions, you can use promise.then(undefined, onRejected), and only specify the callback function in reject. In this case promise.catch(onRejected) would be a better option.

promise.catch(onRejected)
Copy the code

Static Method

Global objects like Promises also have static methods.

Promise.all() and promise.resolve () are helper methods that operate on promises.

The state of the Promise

A Promise object instantiated with New Promise has three states.

  • “has-resolution” – Fulfilled

    Resolve. Ondepressing will be called at this time

  • “has-rejection” – Rejected

    Reject (reject) OnRejected is called

  • “unresolved” – Pending

    It is neither resolve nor Reject. That’s the initial state of the promise object after it’s created

Create a Promise object

function getURL(URL) {
    return new Promise(function (resolve, reject) {
        var req = new XMLHttpRequest();
        req.open('GET', URL, true);
        req.onload = function () {
            if (req.status === 200) {
                resolve(req.responseText);
            } else {
                reject(new Error(req.statusText)); }}; req.onerror =function () {
            reject(new Error(req.statusText));
        };
        req.send();
    });
}
// Run the example
var URL = "http://httpbin.org/get";
getURL(URL).then(function onFulfilled(value){
    console.log(value);
}).catch(function onRejected(error){
    console.error(error);
});
Copy the code

Promise#then

Promise can be written as a method chain

aPromise.then(function taskA(value){
// task A
}).then(function taskB(vaue){
// task B
}).catch(function onRejected(error){
    console.log(error);
});
Copy the code

If each callback function registered in THEN is called a task, then we can use the Promise method chain to write logic that can be processed in a taskA → Task B process.

  • Then registers the callback function when Ondepressing

  • The callback function used when the catch registers onRejected

Promise#catch

Promissory #catch is just a promise. Then (undefined, onRejected); This is just an alias for the method. That is, this method is used to register the callback function when the Promise object state changes to Rejected.

Promise.all

Promise.all takes an array of Promise objects as arguments, and calls the.then method when all the Promise objects in the array are resolved or reject.

Promise.all([request.comment(), request.people()]);
Copy the code

In the above code, request.ment () and request.people() start executing at the same time, and the result of each promise (the parameter value passed in resolve or reject), Is the same order as the Promise array passed to promise.all.

In other words, the. Then array of promises is executed in a fixed order, i.e. [comment, people].