promise

A. Asynchronous causes

Js is single-threaded, can only do one thing at a time, all tasks need to queue, if the task execution event is too long, it will greatly affect the user experience, so JS designed asynchronous mode under the defects of synchronous mechanism

Two. Asynchrony defect => callback hell

To get the results of an asynchronous task, we had to use callback functions so heavily that the code looked messy and even callback hell

function1(function(){// code execution... (ajax1) functions2(function(){// code execution... (ajax2) functions3(function(data3){// code execution... (ajax3) }); . }); });Copy the code

Call back the solution to hell

The Promise object represents an asynchronous operation. There are three states: Pending => Resolved, And Rejected

1, then chain operation usage

        let getToken = function () {
            return new Promise((resolve, reject) => {
                resolve('token')
            })
        }

        let getName = function (token) {
            return new Promise((resolve, reject) => {
                    resolve('Ming')
            })
        }
        let getAge = function (name) {
            return new Promise((resolve, reject) => {
                if (name) {
                    resolve('60')
                }
            })
        }
        getToken().then(res => {
            console.log(res)
            return getName(res)

        }).then(res => {
            console.log(res)
            return getAge()
        }).then(res => {
            console.log(res)
        })
Copy the code

Reject sets the promise state to Rejected when an asynchronous operation fails

        let getAge = function (name) {
            return new Promise((resolve, reject) => {
                if (name) {
                    resolve('60')
                }
                reject('name=>err')
            })
        }   
        getAge().then(res=>{
            console.log(res,'res')
        },err=>{
            console.log(err,'err')})Copy the code

Catch is used to specify the error callback function

        let getAge = function (name) {
            return new Promise((resolve, reject) => {
                if (name) {
                    resolve('60')
                }
                reject('name=>err')
            })
        }   
        getAge().then(res=>{
            console.log(res,'res')
        }).catch(err=>{
             console.error(err,'err')})Copy the code

Promise.all(), wraps multiple Promise instances into a new Promise instance and returns all results

       Promise.all([getToken(),getName(),getAge()]).then(res=>{
            console.log(res)
        }).catch(err=>{
            console.error(err,'err')})Copy the code

5. Promise.race(), which also wraps multiple Promise instances into a new Promise instance, the difference is that the incoming Promise which results get fast, which will be returned, whether success or failure

        Promise.race([getToken(), getName('token'), getAge('token')]).then(res => {
            console.log(res)
        }).catch(err => {
            console.error(err, 'err')})Copy the code

Promise encapsulates the interface request

        const $http = (url, data, method) => {
            method = method.toUpperCase();
            const config = {
                method, url
            }
            if (['GET'.'DELETE'].includes(method)) { config.params = data }
            else { config.data = Qs.stringify(data) }
            return new Promise((resolve, reject) => {
                axios(config).then(response => {
                    let code = response.data.code
                    if (code == 200) {
                        resolve(response.data)
                    }else{
                        reject(response.data)
                    }
                }).catch(err => {
                    reject(err)
                })
            })
        }
Copy the code