While studying ES6 and ES7, I often hear that promises, async await, and Generator are used to handle asynchronous functions, but I don’t know exactly how they are used. So, today special to these three system overview.

The relationship between the three

Async /await is the syntactic sugar of the Generator function and an improvement on the Generator function. It is implemented based on Generator and Promise.

promise

Function: Returns an asynchronous result

function myPromise(isReject,val){
    return new Promise((resolve,reject) = > {
        isReject ? reject('err') : 
        // Use the third argument of setTimeout
        setTimeout(resolve,2000,val)
        //
        setTimeout(() = >{
            resolve(val)
        },5000)})}Copy the code

This function can simulate both success and failure.

Async/await

var myasync =  async function() {
    // this value1 is the resolve value of myPromise. Then, await
    var value1 = await myPromise(false.2)
    return value1
}
// Async returns a promise. Value1 returns a promise wrapped in promise.resolve ()
console.log(myasync().then(res= > console.log(res)))
Copy the code

generator

function * myGenerator() {
    yield myPromise(false.1)}console.log(myGenerator().next())  // {value: Promise, done: false}
console.log(myGenerator().next().value.then((res) = > console.log(res)))
Copy the code

The difference between a generator and a normal function:

function* sum(x) {
    var y = yield x +2;
    return y;
  }
  
  var val = sum(1);
  console.log( val.next()) // { value: 3, done: false }
  console.log( val.next()) // { value: undefined, done: true }

// A real asynchronous execution example
function* sum(){
  var result = yield myPromise(false.3);
  console.log(result);
}
sum.next().value.then(res= > console.log(res))
Copy the code
  • Normal functions don’t have an asterisk. This isgeneratorFunction flag
  • A normal function call returns the result,generatorThe function call does not return the result. Instead, it returns the pointer object val, which has two valuesvalue,done.valuesisyieldThe value of the expression following the statement,doneOnly meetreturnWill becometrue

Difference between Async/await and generator:

var sum = async function (){
  var value2 = await myPromise(false.4);
  return value2;
};
Copy the code
  • asyncjustgeneratorA grammatical sugar, which is equivalent to *,awaitThe equivalent ofyield
  • async andawaitCompared to asterisks andyieldThe semantics are clearer
  • yield Command can only be followed byThunk A function orPromise Object, andasync Function of theawait After the command, you can followPromise Object and primitive type values (numeric, string, and Boolean, but this is equivalent to a synchronous operation)