This is the 17th day of my participation in the August Text Challenge.More challenges in August
What is async function
Async functions are syntactic sugar for Generator functions.
Let’s look at what a Generator is:
function upupup() {
yield 'hi,';
yield 'hello';
return 'bye';
};
var talkToGirl = upupup();
Copy the code
Function talkToGirl, which has two yield (hi and Hello) states inside: hi, Hello, and return (bye).
Generator functions are then called with a pair of parentheses following the function name as normal functions. The difference is that when a Generator function is called, it does not execute. Instead, it returns a pointer to an internal state, an iterator. Each time next is called, the internal pointer executes from the head of the function or from where it last stopped until the next yield or return is reached.
Write it as async, which looks like this:
const talkToGril = async function () {
await upStep(1);
await upStep(2);
await upStep(3);
return;
};
Copy the code
Async is to replace the * of Generator with async and yield with await.
The differences between Async and Generator are mainly reflected in the following four aspects:
One, built-in actuator
Generator functions must be executed by an executor, hence the CO module, while async functions have their own executor. In other words, async functions are executed exactly like normal functions, with only one line.
talkToGril();
Copy the code
The above code calls the asyncReadFile function, which then automatically executes and outputs the final result. This is not at all like a Generator function where you need to call the next method or use the CO module to actually execute and get the final result.
2. Better semantics:
Async and await are semantic clearer than asterisks and yield. Async means that there is an asynchronous operation in a function, and await means that the following expression needs to wait for the result.
Three, wider applicability:
According to the CO module convention, yield can only be followed by Thunk or Promise, while async can be followed by await and Promise and primitive type values (numeric, string, Boolean, etc.). But that automatically changes to an immediate Resolved Promise).
The return value is Promise:
Async functions return a Promise object, which is much more convenient than Generator functions returning an Iterator. You can specify what to do next using the then method.
Further, async functions can be thought of as multiple asynchronous operations wrapped as a Promise object, and await commands are syntactic sugar for internal THEN commands.