[Turn] js async await the ultimate solution for asynchronous

Read catalog

Since there is promise why there async await? Of course promise not perfect asynchronous solutions, while async await the wording seems more simple and easy to understand.

Promise Review

The final status (completed or failed) for indicating a target Promise asynchronous operations, and the value it returns.

Promise Target by keyword  new and constructor to create. Constructor, the one called "handler function" (executor function) as a function of its argument. The "handler function" takes two functions resolve , and  reject as its argument. When the successful completion of the asynchronous task and returns the result value, it calls the  resolve function, and when the asynchronous task fails and returns a failure reason (usually a wrong target), the calls reject functions.

promise state

    pending: an initial state, neither successful nor a failure state
    fulfilled: Operation Success
    rejected: operation failed

promise demo

Copy the code
 1    var promise1 = new Promise(function(resolve, reject) {
 2         setTimeout(function() {
 3             resolve('foo');
 4         }, 300);
 5     });
 6     promise1.then(function(value) {
 7         console.log(value);
 8         // foo
 9     });
10     console.log(promise1);
11     //  [object Promise]
Copy the code

By then external () method to bind success, failure callback function, there is no feeling of before this with ajax similar, but we are then thrown into the callback (), this then chained and support operations, that is, if there is multiple nested so that is constant then ().

async await literally

  Start with the literal meaning to understand, async is "asynchronous" means, and await the meaning of waiting. So it should be well understood async to declare an asynchronous function (actually async function objects), and await an asynchronous wait for the results of the task execution is completed.

Async and await only appear in the function.

async await demo

In the api 1, the results return out 
2 Export getRetailUnitPrice the async function () { 
. 3 = const reqBody the await GET ( '/ Race / SPOT / racespot / Enter / dayahead') 
. 4 return reqBody 
. 5}
Vuex 1 in the results the commit: 
2 // power: before successful output unit 
. 3 getRealTimeRetailUnitPrice the async (the commit {}) { 
. 4 {Output} = const the await getRetailUnitPrice () 
. 5 the commit (types.PLANT_REALTIME_DAYAHEAD, {Output}) 
. 6}
In the code vue 1 
2 {the this the try. Store.dispatch $ ( 'getRealTimeRetailUnitPrice') 
. 3} the catch (E) { 
. 4 the this. $ Message.Error An (E) 
. 5}

async, await how to perform

async to tell the program which is an asynchronous operation, an operator await that await followed by an expression.

async return value

1  // async
2     async function testAsync() {
3         return "hello async";
4     }
5     const data = testAsync();
6     console.log(data);

as the picture shows:

When you call a async function returns a Promise object. According to the interpretation of mdn

  When this function returns a value async, Promise of the resolve method is responsible for transmitting the value;

  When async throws an exception, Promise reject method is also transmitted to the outliers. async function may be await expression, await expression async function will be suspended until the expression Promise after completion of the analysis continues async await later in the code and returns the results to solve.

Note, await keyword only in async function effectively in

Since returns Promise objects, in a case where the outermost layer can not obtain await its return value, then certainly with the original way: then () to handle the chain of objects such as Promise

Copy the code
1     // async
2     async function testAsync() {
3         return "hello async";
4     }
5     let data = testAsync().then( (data) => {
6         console.log(data) // hello async                                                 
7         return data
8     });
9     console.log(data);
Copy the code

If async function does not return a value, so what? It is easy to think that it will return Promise.resolve (undefined).

Promise think about the characteristics of no-wait, so perform async function without await, it will execute immediately return a Promise object, and will not be blocked behind the statement.

await operator

MDN is a description await:

await expression will suspend execution of the current async function, waiting for Promise processing is complete. If normal processing Promise (Fulfilled), which callback parameter as a function of the value of resolve await expressions continue async function. If the Promise to handle exceptions (rejected), await Abnormal expression of Promise will be thrown. Further, if the expression is not a value await operator Promise, returns the value itself.

 Ruan Yifeng teacher's explanation I find it easier to understand:

async function returns a Promise object when the function is executed, the event will be to go back to await until the completion of the trigger asynchronous operation, followed by execution statement after the function in vivo.

Mdn explained according to await execution function suspends the current async and await followed by an expression, i.e., this is a wait await expression (expression that returns the object or promise a specific value):

  •   If this expression if the return is a Promise object, then its return value, in fact, resolve arguments Promise callback function, if the Promise rejected the, await the expression of Promise will throw an exception.
  •   If this expression if the return is a constant, then would this constant into Promise.resolve (xx), the same way if no return value is Promise.resolve (underfind)
1 async function testAwait() {
2          const data = await "hello await";
3          console.log(data)                                          
4         return data
5     }

Output "hello await"

Return promose object success status

Copy the code
. 1 function say () { 
 2 return new new Promise (function (Resolve, Reject) { 
 . 3 the setTimeout (function () { 
 . 4 the let Age = 26 is 
 .. 5 Resolve ( 'Hello, Joel year I $ {age} years'); 
 6} , 1000); 
 . 7}); 
 . 8} 
 . 9 
10 Demo the async function () { 
. 11 V = const say the await (); // output: hello, joel. I am 26 years old this year, waiting for the asynchronous say, if successful, the parameters of the callback function as a result of resole 
12 console.log (v); 
13} 
14 Demo ();
Copy the code

Promise to return the object, a failed state

Copy the code
1 function say () { 
 2 return new new Promise (function (Resolve, Reject) { 
 3 the setTimeout (function () { 
 4 the let Age = 26 
 5 Reject ( `the Hello, Joel, of the exception. This year I $ {age}-year-old` ); 
 . 6}, 1000); 
 . 7}); 
 . 8} 
 . 9 Demo the async function () { 
10 the try { 
. 11 V = const say the await (); // output: hello, joel, abnormality occurs. Year 26 years waiting for this asynchronous I say, if the successful callback resole parameter as a function of the result 
12 is the console.log (V); 
13 is the catch} (E) { 
14 the console.log (E) 
15} 
16} 
. 17 Demo () ;
Copy the code

 Advantages compared to the original Promise async / await then that the processing chain, then do not have to callback nested, as long as can await such as

Copy the code
Sing function. 1 () { 
 2 return new new Promise (function (Resolve, Reject) { 
 . 3 the setTimeout (function () { 
 . 4 Resolve ( `to a good song it ~ ~ ~`); 
 5}, 1000); 
 6} ); 
 . 7} 
 . 8 Demo the async function () { 
 . 9 the try { 
10 V = const say the await (); 
. 11 S = const the await Sing (); 
12 is the console.log (V); // output: hello, joel. This year I am 26 years old 
13 console.log (s) // to a good song it ~ ~ ~ 
14} the catch (E) { 
15 console.log (E) 
16} 
17} 
18 Demo ();
Copy the code

If you use the original Promise is to the callback on then () in.


to sum up

  1. async tell the program which is an asynchronous, awiat pause code execution in async, waiting for the results of the back of the await expression, skip async function, continue to implement the code behind
  2. async function returns a Promise object, when the async function returns a value, resolve method Promise will be responsible for delivering this value; when the async function throws an exception, reject method Promise will pass this outlier
  3. await operator to wait a Promise object, and the object returns the processing result Promise (successfully resolve the function parameter values ​​as await expression), if not waiting Promise object, transformed with Promise.resolve (xx)

Guess you like

Origin www.cnblogs.com/chris-oil/p/11239803.html