JS-ES6 Learning notes-async function (3)

Source: Internet
Author: User

1, the await object behind the command Promise , the result may be rejected , so it is better to put the await command in the try...catch code block.

2, await the asynchronous operation behind multiple commands, if there is no secondary relationship, it is best to let them trigger at the same time.

// notation a let [foo, bar] = await Promise.all ([Getfoo (), Getbar ()]); // notation Two let foopromise == = = await barpromise;

3, the await command can only be used in the async function, if used in ordinary functions, will be error.

function // There's no need for async  . Let docs = [{}, {}, {}];   // may get incorrect results  function (DOC) {    await db.post (DOC);  });

The above code may not work properly, because at this point three operations will be executed concurrently, that is db.post , execution at the same time, not secondary execution. The correct notation is to use for loops.

function DBFUC (db) {  = [{}, {}, {}];    for (let doc of docs) {    await db.post (DOC);  }}

If you do want multiple requests to execute concurrently, you can use the Promise.all method.

4, the implementation of the Async function principle, is to Generator function and automatic actuator, wrapped in a function.

5.

function Loginorder (URLs) {  //  concurrent read remote URL  Const textpromises = urls.map (async URL + = {     = await fetch (URL);     return Response.text ();  });   // output  by order  for (const textpromise of textpromises) {    console.log (await textpromise);}  }

In the above code, although map the parameter of the method is a async function, it is executed concurrently, because only the inside of the async function is secondary execution, the outside is unaffected. The back for..of loop is used internally await , so the output is implemented sequentially.

JS-ES6 Learning notes-async function (3)

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.