This is the 9th day of my participation in Gwen Challenge

introduce

Promise is ES6’s solution to asynchronous programming. A Promise is an object container that stores asynchronous operations (synchronous can be done, but not necessary) inside the container, and promises can get messages about the current asynchronous operation when it executes. This pattern is more powerful and reasonable than a traditional callback.

The Promise asynchronous operation has three states: Pending, fulfilled and Rejected. Nothing other than the result of an asynchronous operation can change this state.

The Promise object has only the state changes from Pending to fulfilled and from pending to Rejected. This is a big pity and rejected, and the state will not change again.

Basic usage

The concept Promise is a constructor that generates a Promise instance object

The syntaxpromise constructor takes a function as an argument when generating the instance object, which takes two arguments (provided by the JS engine)

  • The resolve parameter is a function that changes the state of a Promise from pending to depressing (resolve). It is a function that needs to be called when an asynchronous operation succeeds

  • Reject is a function that changes the state of a Promise from Pending to Reject, which is called when an asynchronous operation fails

Both parameters can pass the parameters they receive

let p = new Promise(function (resolve, reject{
    let num = Math.random()

    if (num > 0.5) {
        resolve(num) // The resolve method was successfully called to pass numelse {
        reject('Failed! '// Fail to call reject, which calls' reject! 'Pay it forward}})Copy the code

prototype.then

Once the concept Promise instance object is generated, the resolve and Reject state callbacks can be used

The syntactic then method takes two functions as arguments

  • Argument one: the callback function that Promise executes on success and accepts the argument that Resolve passes

  • Parameter two The callback that receives reject when the Promise execution fails

Only one of the two functions will be called.

let p = new Promise(function (resolve, reject{
    let num = Math.random()

    if (num > 0.5) {
        resolve(num) // The resolve method was successfully calledelse {
        reject('Failed! '// Call reject
    }
})
       
p.then(
    res= > console.log('success! ' + res), // The resolve callback function
    err= > console.error(err) // reject callback function
)
Copy the code

prototype.catch

The alias for the second parameter of the then method when the state is transferred from Pending to Reject after the concept Promise instance object is generated. Reject Throws exceptions that are caught by a catch

grammar

p.then(
    res= > console.log('success! ' + res), // The resolve callback function
    err= > console.error(err) // reject callback function
)
// can be written as
p.then(res= > console.log('success! ' + res) // The resolve callback function
    .catch(err= > console.error(err)) // reject callback function
Copy the code

prototype.finally

The concept will execute the specified callback function when the promise ends, whether the result is a pity or Rejected. Generally do some asynchronous request cleanup work.

grammar

p.finally(() = > console.log('Asynchronous operation completed with or without success') )

p.then(function(json) { })
  .catch(function(error) { })
  .finally(function() {});Copy the code

all

Concept This method takes multiple Promise objects and returns a promise object. The Promise object method is called when multiple Promises are successfully executed

Note that all promises are successful; If one Promise fails, the all state also fails, and the failure is the result of the first failed Promise.

grammar

 function fakeAjax(timeout, name , isSuccess = true{
    return new Promise((resolve, reject) = > {

        setTimeout(() = > {
            if(isSuccess) {
                resolve(name)
            }else {
                reject(name)
            }
        }, timeout)

    })
}
let p1 = fakeAjax(2500.'p1')
let p2 = fakeAjax(1500.'p2')
let p3 = fakeAjax(800.'p3')

Promise.all([p1, p2, p3]) 
// All promises must be successful to enter then,
The argument to the success callback of then is an array containing the success returns of multiple Promise objects returned by the all method
            .then(res= > console.log(res)) // ['p1','p2','p3']
            .catch(err= > console.error(err) ) 
            
let p1 = fakeAjax(2500.'p1')
let p2 = fakeAjax(1500.'p2'.false)
let p3 = fakeAjax(800.'p3'.false)
// If any Promise fails, all goes into catch
The catch callback takes the return value of the first failed Promise
Promise.all([p1, p2, p3])
            .then(res= > console.log(res)) 
            .catch(err= > console.error(err))  // 'p3'
Copy the code

any

Concept This method takes multiple Promise objects and returns a promise object. The Promise object method is called when one of multiple Promises is successfully executed

Note that if a Promise succeeds, any returns success, the first successful Promise resolve value.

grammar

function fakeAjax(timeout, name, isSuccess = true{
            return new Promise((resolve, reject) = > {

                setTimeout(() = > {
                    console.log(name + '执行完毕')
                    if (isSuccess) {
                        resolve(name)
                    } else {
                        reject(name)
                    }
                }, timeout)

            })
        }

        let p1 = fakeAjax(2500.'p1')

        let p2 = fakeAjax(1500.'p2')

        let p3 = fakeAjax(800.'p3')

        Promise.any([p1, p2, p3])
            .then(res= > console.log(res)) // 'p3'
            .catch(err= > console.error(err))
Copy the code

race

Concept This method takes multiple Promise objects and returns a promise object. As long as there is one finish (success or failure). Returning the Promise object completes the call to the Promise state

grammar

let p1 = fakeAjax(2500.'p1')

let p2 = fakeAjax(1500.'p2')

let p3 = fakeAjax(800.'p3'.false)

Promise.race([p1, p2, p3])
    .then(res= > console.log(res)) 
    .catch(err= > console.error(err)) // 'p3'
    
let p1 = fakeAjax(2500.'p1')

let p2 = fakeAjax(500.'p2')

let p3 = fakeAjax(800.'p3')

Promise.race([p1, p2, p3])
    .then(res= > console.log(res))  // 'p2' 
    .catch(err= > console.error(err))  
Copy the code

allSettled

Concept This method takes multiple Promise objects and returns a promise object. This method will resolve an array that contains all Promise completion information (status: a successful pity, a failed reject, value: a successful return value, reason: a failure reason) until all promises are fulfilled (whether they succeed or fail).

grammar

let p1 = fakeAjax(2500.'p1'.false)

let p2 = fakeAjax(1500.'p2')

let p3 = fakeAjax(800.'p3'.false)

let p4 = fakeAjax(300.'p4')

Promise.allSettled([p1, p2, p3, p4])
            .then(res= > console.log(res)) 
/* res = [{status: "rejected", reason: "p1"}, {status: "fulfilled", value: "p2"}, {status: "rejected", reason: "p3"}, {status: "fulfilled", value: "p4"}, ] */
Copy the code

resolve

Concept This method directly creates a success Promise

grammar

Promise.resolve(10086).then(res= > console.log(res)) / / 10086
Copy the code

reject

Concept This method directly creates a failed Promise

grammar

Promise.reject(new Error('failure')).catch(error= > console.log(error)) // "failed"
Copy the code

Async function

The concept async is an ES7 keyword related to asynchronous operations that are represented in synchronous code

The syntax is a function that uses async key declarations. Rewrite the asynchronous callback code into synchronous code with the await keyword inside the function

function demo () {
     new Promise(function (resolve, reject{
        let num = Math.random()

        if (num > 0.5) {
            resolve(num) // The resolve method was successfully calledelse {
            reject('Failed! '// Call reject
        }
    })
    .then(res= > console.log('success! ' + res))
    .catch(err= > console.error(err) )
}
  
 // The following code is equivalent to the above
 async function asyncDemo({
    try {
        let res = await new Promise(function (resolve, reject{
        let num = Math.random()
        if (num > 0.5) {
                resolve(num) // The resolve method was successfully calledelse {
                reject('Failed! '// Call reject}})console.log(res, 'async')}catch (err) {
        console.log('Error:'+ err)
   }
}

asyncDemo()
Copy the code

Pay attention to

1. asyncThe return value of the function, not the return value of an ordinary object, butPromiseobjectasync function test({
        return 'hello world'
}

 New Promise((resolve) => resolve('hello world'))
console.log(test()) // Promise {<resolved>: "hello world"}
test().then(r= > console.log(r)) // 'hello world'
Copy the code

Example use of Axios (axios is a Promise-based HTTP library that can be used in browsers and Node.js)

<! -- Introducing axios tripartite library --><script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
// Asynchronous functions
 async function test({
     let res = await axios('http://musicapi.leanapp.cn/search?keywords=')
     console.log(res) 
}
// A normal function
function test({
   axios('http://musicapi.leanapp.cn/search?keywords=二')
     .then(res= > {
           console.log(res,'12313')})}</script>
Copy the code

Practice using Promise to encapsulate ajax’s GET methods

 function httpGet(url{
        return new Promise((resolve, reject) = > {
            let xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function ({
                if (xhr.readyState == 4) {
                    if (xhr.status == 200) {
                        / / success
                        let res = JSON.parse(xhr.responseText)
                        resolve(res)
                    } else {
                        / / fail
                        reject(new Error('failure'))
                    }

                }
            }
            xhr.open("GET", url, true);
            xhr.send();
        })     
}


httpGet('in http://musicapi.leanapp.cn/search?keywords=)
       .then(res= > console.log(res))
       .catch(err= > console.log(err))
Copy the code