The async,await of NODEJS study notes

Source: Internet
Author: User

Async should be the simplest and most straightforward asynchronous scheme in the Nodejs, and the async function is actually the syntax sugar of the generator function, eliminating callback's callback hell, Generator yield next,promise. Then. Catch to make the code look more like a synchronous process scenario and flatter. Let's look at an example:

Here we are going to implement a pause function, enter n milliseconds, then pause for n milliseconds before proceeding down.

Here is a function function or it can be other time-consuming operations.            var sleep = function (time) {return new Promise (function (resolve, reject) {setTimeout (function () {        Resolve ();    }, time);    })};var start = Async function () {//is used here as intuitive as synchronous code Console.log (' Start ');    Await sleep (3000);  Console.log (' End '); };start ();

The console outputs start first, and after 3 seconds, the output end.

How async functions are used:

Async is essential for the Async function MyFunc () {...//Common code await ...//1 time consuming code or executing time-consuming function and waiting to finish The code let res = await ...//2 time-consuming code or executing time-consuming functions and getting return results ...}


Error capture Mode:

Async uses Try.catch to catch error async function MyFunc () {try{...} catch (e) {throw e; }}

This article refer to Http://cnodejs.org/topic/5640b80d3a6aa72c5e0030b6

This article is from "__ No acted" blog, please make sure to keep this source http://wuzishu.blog.51cto.com/6826059/1894990

The async,await of NODEJS study notes

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.