Home  >  Article  >  Web Front-end  >  Introduction to the difference between Generator function and async function

Introduction to the difference between Generator function and async function

不言
不言forward
2019-04-04 11:28:152313browse

This article brings you an introduction to the difference between generator function and async function. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Generator function:

The Generator function is an asynchronous solution provided by ES2015, which is very different from ordinary functions;

Features:

1. Follow the function keyword with a (*) sign;

2. Use the yield expression as a state inside the function body;

The Generator function returns a traverser , each state can be traversed through the for...of method;

Usage:

Executes the Generator and does not execute it immediately. It returns a traverser, which calls next() and throw() Or return() executes the next state, captures errors or ends the traverser;

async function:

The async function is the asynchronous function syntax provided by ES2017, which is the generator's Syntactic sugar, but its usage is still very different from the Generator function;

Features:

1. Follow the async keyword in front of the function keyword;

2. Use await expression inside the function body;

async function returns a promise object;

Usage:

Executing the async function will execute immediately, just like a normal function, but returns A promise object;

Comparison between the two:

1. Generator appears in ES2015, async appears in ES2017, async is the syntactic sugar of Generator;

2. The execution methods are different. Generator execution requires the use of an executor (next() and other methods); the async function has its own executor, which is the same as the execution of ordinary functions;

3. The syntax and semantics of async are more Clearly, async means asynchronous, await means waiting; the semantics of the (*) number and yield in the Generator function are not so direct;

4. Yield in Generator can only be followed by a Thunk function or a Promise object; and The await in the async function can be followed by a promise object or a primitive type value (which will be automatically converted to a promise object that immediately resolves);

5. The return value is different. Generator returns a traverser, compared to async which returns a promise object. Operation is more troublesome.

【Related recommendations: JavaScript video tutorial

The above is the detailed content of Introduction to the difference between Generator function and async function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete