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 is
generator
Function flag - A normal function call returns the result,
generator
The function call does not return the result. Instead, it returns the pointer object val, which has two valuesvalue,done
.values
isyield
The value of the expression following the statement,done
Only meetreturn
Will becometrue
Difference between Async/await and generator:
var sum = async function (){
var value2 = await myPromise(false.4);
return value2;
};
Copy the code
async
justgenerator
A grammatical sugar, which is equivalent to *,await
The equivalent ofyield
async
andawait
Compared to asterisks andyield
The semantics are cleareryield
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)