JS-ES6 Learning Notes-async functions

Source: Internet
Author: User
Tags readfile

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 ());};

asyncas 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 ());};

asyncThe 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.

    1. 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

    2. Better semantics. asyncand await , compared to asterisks and yield , the semantics are clearer. asyncindicates that there is an asynchronous operation in the function that await indicates that the expression immediately following it needs to wait for the result.
    3. 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).
    4. 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.