"Probably probably is" the best JavaScript asynchronous scheme at the moment Async/await__java

Source: Internet
Author: User

Building an application will always face asynchronous calls, whether in the Web front-end interface or the Node.js server, where JavaScript processing asynchronous calls is a disgusting thing. Previously only through the callback function, and then gradually evolved a lot of programs, and finally Promise to simple, easy to use, compatibility good win, but there are still a lot of problems. In fact, JavaScript has always wanted to solve this problem at the language level, in the ES6 has supported the original Promise, but also introduced the generator function, finally in ES7 decided to support async and await.

Basic Syntax

How does async/await solve the asynchronous invocation? In short, the asynchronous operation is written in synchronous notation. Let's take a look at the most basic syntax (ES7 code fragment):

Const F = () => {return
  new Promise (Resolve, Reject) => {
    settimeout (() => {resolve
      (123);
    }, 2 );
  };

Const TESTASYNC = Async () => {
  Const T = await f ();
  Console.log (t);
};

Testasync ();

First defines a function f, which returns a Promise, and delays 2 seconds, resolve and passes in the value 123. The Testasync function uses the keyword async when it is defined, and then the await is used in conjunction with the function body, and finally executes the testasync. The entire program will output 123 in 2 seconds, that is, the constant T in Testasync gets the value of resolve in F, and the execution of the following code is blocked through the await until the F-this asynchronous function executes. contrast Promise

Just a simple call, it has been able to see the powerful async/await, write code can very gracefully handle asynchronous functions, completely farewell to callback nightmares and countless then methods. Let's take a look at the comparison with Promise, the same code, and if you use Promise completely, what's the problem?

Const F = () => {return
  new Promise (Resolve, Reject) => {
    settimeout (() => {resolve
      (123);
    }, 2 );
  };

Const TESTASYNC = () => {
  f (). Then ((t) => {
    console.log (t);
  });

Testasync ();

It's easy to see from snippets that Promise doesn't fix things, like having a lot of then methods, the whole piece of code is full of Promise methods, not the business logic itself, and every then method is a separate scope, and if you want to share data, It is necessary to expose some of the data to the outermost layer and assign a value within the then. However, Promise is very good for the encapsulation of asynchronous operations, so Async/await is based on Promise, await to receive a Promise instance. contrast RXJS

RXJS is also a very interesting thing to do with asynchronous operations, which is more capable of handling data operations based on streaming. For example, for example, the HTTP request returned in ANGULAR2 is a rxjs constructed observable Object, and we can do this:

$http. Get (URL)
  . Map (function (value) {return
    value + 1;
  })
  . Filter (function (value) {return
    value!== null;
  })
  . ForEach (function (value) {
    console.log (value);
  })
  . Subscribe (function (value) {
    console.log (' do something. ');
  }, Function (err) {
    console.log (err);
  });

If the ES6 code can be further concise:

$http. Get (URL) 
  . Map (value => value + 1) 
  . Filter (value => value!== null) 
  . ForEach (Value => Console.log (value)) 
  . Subscribe ((value) => { 
    console.log (' do something. '); 
  }, (Err) => { 
    Console.log (err); 
   

Can be seen RXJS for such data can do a similar flow-style processing, but also very elegant, and rxjs strong is that you can also do the data cancellation, monitoring, throttling and so on operations, here not one example, interested in the words can go to see the Rxjs API.

Here to explain that RXJS and async/await together is also possible, observable object has a Topromise method, you can return a Promise object, can also be combined with await use. Of course, you can also use only async/await with underscore or other libraries, but also to achieve a very elegant effect. In short, RXJS and async/await do not conflict. Exception Handling

By using async/await, we can work with Try/catch to capture problems during asynchronous operations, including the Reject data in Promise.

Const F = () => {return
  new Promise (Resolve, Reject) => {
    settimeout (() => {reject
      (234);
    }, 20 );
  };

Const TESTASYNC = () => {
  try {
    const T = await f ();
    Console.log (t);
  } catch (Err) {
    console.log (err);
  }
;

Testasync ();

The code fragment changes the resolve in the F method to reject, and in Testasync, the Reject data is captured by catch, and the output err has a value of 234. Try/catch should also pay attention to the scope and level when using. If a try range contains multiple await, the catch returns the value or error of the first reject.

Const F1 = () => {return
  new Promise (Resolve, Reject) => {settimeout (
    () => {reject ()
      ;
    }, 2 );
  };

Const F2 = () => {return
  new Promise (Resolve, Reject) => {settimeout (
    () => {reject
      (222);
    }, 3000);
  };

Const TESTASYNC = () => {
  try {
    const T1 = await F1 ();
    Console.log (t1);
    Const T2 = await F2 ();
    Console.log (T2);
  } catch (Err) {
    console.log (err);
  }
;

Testasync ();

such as code snippets

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.