Use async/await in JavaScript ES7 to resolve callback function nesting issues

Source: Internet
Author: User
Tags sleep function

Original link: http://aisk.me/using-async-await-to-avoid-callback-hell/

The most painful thing in JavaScript is the callback function nesting problem. In the past, in the browser, because communication with the server is a relatively expensive operation, so the more complex business logic is often placed on the server side, the front-end JavaScript only need a few times the AJAX request to get all the data.

However, in the era of WebApp, the front-end business logic is becoming more and more complex, often several AJAX requests depend on each other, some requests depend on the previously requested data, some requests need to be done in parallel. And in a back-end JavaScript environment like node. JS, the problem is more noticeable because of the large number of IO operations that are required. Using callback functions to organize your code at this time can often lead to code that is difficult to read.

Now the most popular way to solve this problem is to use Promise, which can flatten nested callback functions. But writing code and reading is still an extra burden.

Another scenario is to use the new generator in ES6 because the essence of generator is to pause a function and save the context and restore the state when it is re-invoked. The Co module is a good package. But this slightly abused the feeling of generator characteristics.

ES7 has a more standard solution, adding a async/await of two keywords. Async can declare an asynchronous function that needs to return a Promise object. Await can wait for a Promise object to resolve and get the result.

For example, in the past we could not use the common sleep function in JavaScript, we could only use SetTimeout to register a callback function and execute it after a specified time. With async/await, we can do this:

async function sleep(timeout) {    return new Promise((resolve, reject) => {    setTimeout(function() {      resolve();    }, timeout);  });}(async function() {  console.log(‘Do some thing, ‘ + new Date());  await sleep(3000);  console.log(‘Do other things, ‘ + new Date());})();

Execute this code to see the results in the terminal:

Do some thing, Mon Feb 23 2015 21:52:11 GMT+0800 (CST)  Do other things, Mon Feb 23 2015 21:52:14 GMT+0800 (CST)  

In addition, the Async function can return the result and throw an exception normally. Await function call to get the result, try/catch on the outer bread can catch the exception. Here is an example of getting data from the watercress API:

 var Fetchdoubanapi = function () {return new Promise ((resolve, reject) = = {var xh    R = new XMLHttpRequest (); Xhr.onreadystatechange = function () {if (xhr.readystate = = = 4) {if (Xhr.status >= && Xhr.stat          US <) {VAR response;          try {response = Json.parse (Xhr.responsetext);          } catch (e) {reject (E);          } if (response) {Resolve (response, Xhr.status, XHR);        }} else {reject (XHR);    }      }    };    Xhr.open (' GET ', ' Https://api.douban.com/v2/user/aisk ', true);    Xhr.setrequestheader ("Content-type", "Text/plain");  Xhr.send (data); });};(    Async function () {try {Let result = await fetchdoubanapi ();  Console.log (result);  } catch (E) {console.log (e); }})();

ES7 is still in the draft phase, so what do you want to do with this feature now? You can try one of Google's JavaScript precompiled traceur, which compiles a high version of JavaScript into a ES5 code that has been experimentally supported by async/await (you need to use--experimental to specify on). Traceur can be used directly on the backend or in the browser. In addition, there are some polyfill modules, such as this, if used only in the node. JS Environment.

Use async/await in JavaScript ES7 to resolve callback function nesting issues

Related Article

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.