The basic use

Producer:

Resolve (value) : If the task completes successfully with the result value.

Reject (error) : Error is the error object if an error occurs.

let promise = new Promise(function(resolve, reject) {
    Executor (producer code)
});
Copy the code

The arg argument in new Promise(ARG) is the function that the generator executes

Consumer:

Then () :

  • The first argument to.then is a function that will run after the Promise Resolved and receive the result.

  • The second argument to.then is also a function that runs after the Promise Rejected and receives an error.

.catch() : Catches errors

Finally () : Finally executes


An example:

// Step 1: Model layer interface encapsulation
const promise = new Promise((resolve, reject) = > {
    // Do asynchronous tasks (such as ajax request interface, temporarily replaced by timer)
    setTimeout(function () {
        var data = { retCode: 0.msg: 'qianguyihao' }; // Data returned by the interface
        if (data.retCode == 0) {
            // Called when the interface request succeeds
            resolve(data);
        } else {
            // Called when the interface request fails
            reject({ retCode: -1.msg: 'network error'}); }},1000);
});

// Step 2: business layer interface call. The data is passed in from resolve and Reject, which is the data taken from the interface
promise.then((data) = > {
    // Get a normal result from resolve
    console.log(data);
}).catch((data) = > {
    // Get abnormal result from reject
    console.log(data);
});
Copy the code

Promise the chain

Promise API

Promise.all(with logic)

let getInfoA = new Promise((resolve, reject) = > {
    console.log('Little A is executing.')
    resolve()
})
let getInfoB = new Promise((resolve, reject) = > {
    console.log('Little B is executing.')
    resolve()
})
let getInfoC = new Promise((resolve, reject) = > {
    console.log('Little C is executing.')
    resolve()
})
Promise.all([getInfoA, getInfoB, getInfoC]).then(res= > {
   console.log('It's all done! ')})Copy the code

Notice that the order of the elements in the resulting array is the same as in the source Promise. Even though the first promise took the longest to resolve, it was still the first in the result array.

If any promise is rejected, the promise returned by promise. all is immediately rejected, with this error.

Promise.race(or logic)

let getInfoA = new Promise((resolve, reject) = > {
    console.log('Little A is executing.')
    setTimeout((err= > {
        resolve('Little A is the fastest')}),1000)})let getInfoB = new Promise((resolve, reject) = > {
    console.log('Little B is executing.')
    setTimeout((err= > {
        resolve('Little B is the fastest')}),1001)})let getInfoC = new Promise((resolve, reject) = > {
    console.log('Little C is executing.')
    setTimeout((err= > {
        resolve('Little C is the fastest')}),1002)})Promise.race([getInfoA, getInfoB, getInfoC]).then(res= > {
    console.log(res)
})

/* Little A starts to execute little B starts to execute little C starts to execute little A the fastest */
Copy the code

Like promise. all, promise. race takes an array of Promise objects as arguments, except that the. Then method can be called when one of the Promsie states in the array changes to Resolved or Rejected.

Async and await

Async:

  • Make this function always return a promise

  • Run with await inside the function

Await: Make the JavaScript engine wait until the promise completes (settle) and returns the result. let value = await promise;

async function f() {
    let promise = new Promise((resolve, reject) = > {
        setTimeout(() = > resolve("done!"), 1000)});let result = await promise; // Wait until promise resolve(*)
    alert(result); // "done!"
}
f();
Copy the code