Promise: Promise: promise: promise: promise: promise: Promise: Promise: Promise Next, combine generator to explain to everybody.

First look at the code:

var pro = function() {return new Promise((resolve,reject){
        if(true){
            resolve('success')}else{
            reject('error') } }) } var p = pro(); P.t hen (v = > console. The log (v), e = > console. The log (e)) success, errorCopy the code

This is the most basic use of Promise, overcoming the problem of nested layers of callback functions

Next look at the generator

Generator is a function that generates an iterator object, as shown in the code below:

function* gen(){
    yield 'hello harden'
    yield 'hello world'} var g = gen() --> iterator g.ext () --> {value:'hello harden'.done:false}
g.next() --> {value:'hello world'.done:true}
Copy the code

The generator function returns an iterator. The iterator must be returned to the first yield function by calling the next() method. The done attribute of the returned value determines whether the iterator is finished or not.

Finally, async and await

var pro = function() {return new Promise((resolve,reject){
        resolve('success')
    }
}
async function asy() {let a = await pro()
    return a
}
asy().then(v=>console.log(v)) 'success'
Copy the code

Does anyone notice the difference between Async and Generator? Genertor returns an iterator, while Async returns a Promise. The generator manually calls the next method to get the value, while async automatically starts the iteration, making asynchronous and synchronous procedures written in the same way. Of course, there are also co and thunk modules that can automatically start generator iteration.

Summary: This article briefly introduces the use of promise/Generator/async, in order to record my understanding of ES6 asynchronous, welcome your criticism and correction, email: [email protected]