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