In the asynchronous nature of the front end ES7: async, await.

The front end of the asynchronous nature proposed in the latest ES7 (ES2017): async, await.

What is async, await?

async suggests that it is "asynchronous" means, async is used to declare a function is asynchronous. And await literally means "wait" means, is waiting for the asynchronous completion. Async and await only be used in the function

Usually async, await follow Promise are used together. Why do you say? Because the object is a Promise while async async returned on any suitable type of function. Such await result is a Promise objects (if not the object, then it async Promise to return what it is);

After getting await Promise objects Promise to wait for the next resolve or reject.

Look at a simple code:

async function testSync() {
     const response = await new Promise(resolve => {
         setTimeout(() => {
             resolve("async await test...");
          }, 1000);
     });
     console.log(response);
}
testSync();//async await test...

So a simple async, await an asynchronous complete. Use async, await the completion of asynchronous operation code is written and read more like a synchronous or easier to understand.

 async, await serial parallel processing

Serial: waiting in front of the latter is then performed await a await execution, and so on

async function asyncAwaitFn(str) {
    return await new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(str)
        }, 1000);
    })
}

const serialFn = async () => { //串行执行

    console.time('serialFn')
    console.log(await asyncAwaitFn('string 1'));
    console.log(await asyncAwaitFn('string 2'));
    console.timeEnd('serialFn')
}

serialFn();

 

 

 

You can see the total time for the two thousand two milliseconds await serial execution.

Parallel: a plurality promise direct initiation request (before performing async location function), and then to await operation.

async function asyncAwaitFn(str) {
    return await new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(str)
        }, 1000);
    })
}
const parallel = async () => { //并行执行
    console.time('parallel')
    const parallelOne = asyncAwaitFn('string 1');
    const parallelTwo = asyncAwaitFn('string 2')

    //直接打印
    console.log(await parallelOne)
    console.log(await parallelTwo)

    console.timeEnd('parallel')


}
parallel()

 

 

 

We can see that by printing with respect to serial execution, doubling efficiency. In parallel to the execution request of the asynchronous operation and then async await its result, a plurality of serial to parallel request code can be performed faster and more efficient.

async, await error handling

JavaScript asynchronous request fails there will certainly be a request, the above also said the async returns a Promise object. Since it is a Promise to return the object, then it is an asynchronous request processing when an error occurs we will deal with the status of a reject.

Promise reject the request in the time when we can use the catch. In order to maintain the robustness of the async code, await when we use try catch to handle the error.

function catchErr the async () { 
      the try { 
          const = errRes the await new new Promise ((Resolve, Reject) => { 
                the setTimeout (() => { 
                    Reject ( "HTTP error ..."); 
                 }, 1000); 
           ); 
                // after the usual we can also await request success in determining the current status is not by 200 to determine whether the request is successful 
                // the console.log (errRes.status, errRes.statusText); 
        } the catch (ERR) { 
             the console.log (ERR); 
        } 
} 
catchErr (); // HTTP error ...

These are async, await use try catch error handling.

 

Although async, await also used to reduce the Promise but then makes the whole process Promise asynchronous request code a lot of refreshing.

These are the individuals ES7 async, await some personal understanding, there are other subsequent updates will supplement, not a place to write the great God welcome you correct me, thank you!

 Original link: https://www.cnblogs.com/leungUwah/p/7932912.html

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------

expand:

console.time usage and console.timeEnd

console.time and console.timeEnd these two methods can be used to allow developers to measure a WEB javascript script execution time consumption. With more and more important WEB application, JavaScript execution performance has received increasing attention, WEB developers know some performance testing machine is a must. console.time and console.timeEnd introduced today is one of them.

console.time approach is to start the computation time, console.timeEnd is stop the clock, the output of the script execution time.

// start timer 
console.time ( 'testForEach'); 

// (write test code) 

// stop the clock, the output time 
console.timeEnd ( 'testForEach'); 

// 4522.303ms

Both methods can be a successor parameter, as the name of the timer, its role is to run in parallel each timer clear division code. Console.timeEnd will call for immediate execution of the output consumed by the total time, in milliseconds.

Note: console.time ( "cycle start time") pass parameters console.timeEnd parameter ( "cycle start time") must be consistent, otherwise the output is not timing, timing is 0ms, if the default does not pass parameters: default : 08080ms

There are many ways to test JavaScript performance, but console.time / timeEnd two methods are the most basic and straightforward techniques.

Solve IE8 does not support console

Solve IE8 does not support the console, will complain when the code contains console

//解决 IE8 不支持console
window.console = window.console || (function () {
    var c = {}; c.log = c.warn = c.debug = c.info = c.error = c.time = c.dir = c.profile
    = c.clear = c.exception = c.trace = c.assert = function () { };
    return c;
})();

Original link: https://blog.csdn.net/longzhoufeng/article/details/78801042

 

Guess you like

Origin www.cnblogs.com/520BigBear/p/11589228.html