1. The async function is the syntactic sugar of the Generator function. The preceding article has a Generator function that reads two files sequentially.
varFS = require (' FS ');varReadFile =function(fileName) {return NewPromise (function(Resolve, Reject) {Fs.readfile (FileName,function(Error, data) {if(Error) reject (error); Resolve (data); }); });};varGen =function* () { varF1 = Yield readFile ('/etc/fstab '); varF2 = yield readFile ('/etc/shells '); Console.log (F1.tostring ()); Console.log (F2.tostring ());};
async
as a function, this is the following.
var function () { var f1 = await readFile ('/etc/fstab '); var f2 = await readFile ('/etc/shells '); Console.log (F1.tostring ()); Console.log (F2.tostring ());};
async
The function is to replace the asterisk () of the Generator function with a *
async
yield
await
.
2, the async
function of the Generator function improvement, reflected in the following four points.
- Built-in actuator. The
async
function comes with an actuator. That is, the async
execution of the function is identical to the normal function, as long as one line.var result = Asyncreadfile ();
The above code calls the asyncReadFile
function and then it executes automatically, outputting the final result. This is not exactly like the Generator function, which requires calling the next
method
- Better semantics.
async
and await
, compared to asterisks and yield
, the semantics are clearer. async
indicates that there is an asynchronous operation in the function that await
indicates that the expression immediately following it needs to wait for the result.
- Wider applicability. The
yield
command can be followed only by the Thunk function or the Promise object, and async
after the command of the function, the value of the await
Promise object and the original type (numeric, string, and Boolean values, but this is equivalent to a synchronous operation).
- The return value is Promise. The
async
return value of the function is a Promise object, which is much more convenient than the Iterator object, which is the return value of the Generator function. You can use then
the method to specify the next action.
Further, the async
function can be thought of as multiple asynchronous operations, packaged into a Promise object, and the await
command is then
the syntax of the internal command of the sugar.
3, async
the function returns a Promise object, you can then
add a callback function using the method. When the function executes, it returns when it is encountered, waits for the await
asynchronous operation to complete, and then executes the statement behind the function body.
function Getstockpricebyname (name) { var symbol = await getstocksymbol (name); var stockprice = await getstockprice (symbol); return StockPrice;} Getstockpricebyname (' goog '). Then (function (result) { console.log (result);});
The keyword in front of the function async
indicates that there is an asynchronous operation inside the function. When the function is called, an object is returned immediately Promise
.
4, another example, specify how many milliseconds to output a value.
function Timeout (ms) { returnnew Promise ((resolve) = { setTimeout (resolve, MS); function asyncprint (value, MS) { await timeout (ms); Console.log (value);} Asyncprint (' Hello World ', 50);
5, the Async function has a variety of use forms.
//function DeclarationAsyncfunctionfoo () {}//function Expressionconst FOO = Asyncfunction () {};//methods of the objectLet obj ={Async foo () {}};obj.foo (). Then (...)//method of Classclass Storage {constructor () { This. cachepromise = Caches.open (' Avatars '); } async Getavatar (name) {Const cache= await This. cachepromise; returnCache.match ('/avatars/${name}.jpg '); }}const Storage=NewStorage (); Storage.getavatar (' Jake '). Then (...);//Arrow Functionsconst FOO = async () = {};
JS-ES6 Learning Notes-async functions