The world of Javascript is single-threaded, giving rise to many problems that need to be solved asynchronously, such as network operations and browser events.

In the past, such problems were usually solved through callbacks or AJAX, but since ES6, promises have been included in the syntactical specification and implemented uniformly by browsers.

Promise

If we wanted to use AJAX for asynchronous operations, we could write:

request.onreadystatechange = function () {
    if (request.readyState === 4) {
        if (request.status === 200) {
            return success(request.responseText);
        } else {
            returnfail(request.status); }}}Copy the code

Success and FAIL are easy to write, but when I need multiple asynchronous operations, it is difficult to reuse this code. Each time success and fail are judged differently, and the whole section needs to be copied.

Return new Promese(resolve,reject)=>{})

Resolve is equal to success reject is equal to fail

then(), catch()

Borrow this code from Liao Xuefeng teacher:

// Execute the function
function test(resolve, reject) {
    var timeOut = Math.random() * 2;
    log('set timeout to: ' + timeOut + ' seconds.');
    setTimeout(function () {
        if (timeOut < 1) {
            log('call resolve()... ');
            resolve('200 OK');
        }
        else {
            log('call reject()... ');
            reject('timeout in ' + timeOut + ' seconds.');
        }
    }, timeOut * 1000);
}

/ / Promise object
var p1 = new Promise(test);
var p2 = p1.then(function (result) {
    console.log('Success:' + result);
});
var p3 = p2.catch(function (reason) {
    console.log('Failure:' + reason);
});

Copy the code

Start by creating an execution function and writing conditions for resolve and reject. We then create a Promise object, and if the function succeeds, use then() to proceed to the next step. If the function fails, the error is caught by catch().

After piecing together:

new Promise(test).then(function (result) {
    console.log('Success:' + result);
}).catch(function (reason) {
    console.log('Failure:' + reason);
});
Copy the code

Promise.all()

The promise.all () method accepts an iterable of promises. Array, Map, and Set are all ES6 iterable types), which wraps multiple Promise instances and generates and returns a new Promise instance.

This method returns when all promise instances in the PROMISE array become resolve, passing all results to the Results array. Any promise in the promise array is reject, the entire promise. all call terminates immediately and returns a reject new Promise object.

let p1 = Promise.resolve(1),
    p2 = Promise.reject(2),
    p3 = Promise.resolve(3);
Promise.all([p1, p2, p3]).then(function (results) {
    // The then method is not executed
    console.log(results); 
}).catch(function (e){
    // The catch method will be executed with the output: 2
    console.log(2);
});
Copy the code

Promise.race()

The promise.race () method accepts an iterable of promises. Array, Map, and Set, all of which are ES6 iterable types, return resolve or reject if any of the promises executes successfully. Promise.race() also returns resolve or reject.

const promise1 = new Promise((resolve, reject) = > {
  setTimeout(resolve, 500.'one');
});

const promise2 = new Promise((resolve, reject) = > {
  setTimeout(resolve, 100.'two');
});

Promise.race([promise1, promise2]).then((value) = > {
  console.log(value);
  // Both resolve, but promise2 is faster
});
Copy the code

As shown above, promisE1 races with PromisE2. If 100ms < 500ms, PromisE2 is returned.