ES6 the Promise, async & await from entry to the master!

1, Promise objects

①: Promise can be seen as a container, inside the container filled until the end of next asynchronous operation;

②: Promise for three states: pending (in progress), fulfilled (been successful) and rejected (failed);

③: state once started, only two possibilities: from pending from pending changes to become fulfilled and rejected, and there will only be a final result;

④: Promise object is a constructor to generate Promise example, a receiving state of the two treatments carried callback function (resolve, resject);

2, Promise basis using

    var Promise_1 = new Promise((resolve, reject) => {
        //异步操作
        setTimeout(() => {
            let Data = true //判断条件
            if (Data) {
                resolve('异步执行成功!') //操作成功
            } else {
                reject('异步执行失败!') //操作失败
            }
        }, 1000)
    })

    Promise_1.then(res => { //then接收成功状态
        console.log(res)
    }).catch(error => { //catch捕获异常
        console.error(error)
    })

 

Promise using literal receiving a return value, to create new instances Promise keywords, instance receives a callback function, carry resolve, reject two methods;

After the instance generator may be used .then () / catch () method returns the state value received Promise.;

The above code, after the new instance Promise successfully performed immediately, Data determination condition is true, so the resolve call method, and then the method specified callback function

Number, the current script will perform all tasks complete synchronization will be performed, so the output is' asynchronous execution success! '.

3, Promise chained calls

    var Promise_1 = new Promise((resolve, reject) => {
        //异步操作
        setTimeout(() => {
            let Data = true //判断条件
            if (Data) {
                resolve('异步执行成功!') //操作成功
            } else {
                reject('异步执行失败!') //操作失败
            }
        }, 1000)
    })

    Promise_1.then(res => { //then接收成功状态
        console.log(res)
        return res + '链式调用1'
    }).then(res => {
        console.log(res) //异步执行成功!链式调用1
    })

The so-called chained calls, then that may have been down, assuming that the first time we get the data required before they can continue to be used again after asynchronous processing, you will need to chain

Invocation, very simple only need to return to the current data at the time then in.

4, Promise performed simultaneously

Scenario: Suppose you want to get a map at the same time Baidu, Netease news, beep beep Mile Mile three sites open data, at this time we need to send three different asynchronous request

To obtain the data, how to do it? Promise.all () a good solution to this need.

    var baidu = new Promise((resolve, reject) => {
        setTimeout(() => { resolve('百度数据')}, 1000)
    })
    var wnagyi = new Promise((resolve, reject) => {
        setTimeout(() => { resolve('网易数据')}, 2000)
    })
    var bili = new Promise((resolve, reject) => {
        setTimeout(() => { resolve('哔哩哔哩数据')}, 500)
    })
    Promise.all([baidu, wnagyi, bili]).then(res => {
        console.log(res) //["百度数据", "网易数据", "哔哩哔哩数据"]
    }).catch(err => {
        console.error(err) //捕获异常
    })

 Note that Promise.all () array literal argument is composed of all Promise instances, the finished result is a number composed of all the output of the

group;

 5、async / await 

First understand async did what? Let's write-period simple code to see what the async function return values ​​exactly?

    async function testAsync() {
        return 'hello async'
    }

    console.log(testAsync()) //输出 Promise对象

See it dawned on output - output is a Promise object.

If you need to get testAsync function return value .then we only need to use the prototype Promise () method; function because if  return an amount directly,

This amount will directly by async  Promise.resolve() encapsulated into objects Promise;

    async function testAsync() {
        return 'hello async'
    }

    testAsync().then(res => {
        console.log(res) //输出 hello async
    })

In general, all that await in the function execution is complete with a wait of async. However, according to Syntax , the await waiting is an expression, the results of this expression is Promise objects or other values.

Because async function returns a Promise object, await the return value can be used to wait for an async function - this can also be said to await waiting for async function, but to be clear, and so it is actually a return value . To note that it can wait for the results of any expression, therefore, await behind the actual function call can be accessed by ordinary direct or amount. Therefore, the following example can run correctly:

    function testAsync() { //只有返回值、没有返回Promise的函数
        return 'hello async'
    }

    function testPromise() { //返回Promise的函数
        return new Promise(resolve => {
            resolve('hello Promise')
        })
    }

    async function test() {
        var Async_1 = await testAsync()
        var Promise_1 = await testPromise().then()
        console.log(Async_1) //输出 hello async
        console.log(Promise_1) //输出 hello Promise
    }
    test() //执行

From the above, as long as the function await the return value of that is down with a await!


If my blog to help you solve development problems, please do not mean your little hearts Oh!


● If there are errors welcome that, timely correction ●

Published 18 original articles · won praise 91 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_43471802/article/details/104943974