• notice
  • Congratulations on the launch of the Sought Tech site

The async-await method for eliminating asynchronous callbacks

Today, the editor will share with you the relevant knowledge points of the method of async-await to eliminate asynchronous callbacks. The content is detailed and the logic is clear. I believe that most people still know this knowledge too well, so I share this article for your reference. I hope After reading this article, everyone has gained something, let's take a look at it together.

    1. Walk into the principle of Async-await

    1. Principle 1

    The async function returns a Promise object, and you can use the then method to add a callback function. for example:

    // async returns a Promise object?
    async function testAsync () {
          return 'hello' ; //If the return value of the Promise object in the previous article is not a Promise, it will be converted to a Promise through Promise.resolve(), and then processed
    }
    const result = testAsync()
      console .log(result); //Promise { 'hello' } indicates that async returns a Promise object

    So since async returns a Promise object, then the function behind async can be connected to .then() or .catch()...? We'll find out when we try it.

    // async returns a Promise object, and can it accept the Promise method?
    async function testAsync () {
          // await await wait or promise object
         return 'hello'
    }
    testAsync()
         .then( ( result )=> {
              console.log(result);
         })
         .catch( ( error )=> {
              console.log(error);
         })
    //hello mom! Printed! It shows that what async returns is a Promise object, and it can accept the method of Promise, and! !! The default state is resolved

    The above code shows that the value returned by the return statement inside the async function will become the parameter of the then method callback function

    2. Principle 2

    When an error is thrown inside the async function, it will cause the returned Promise object to change to the reject state. The thrown error object will be received by the second callback function of the .then() method or the callback function of the .catch() method.

    // An error is thrown inside the async function or the Promise state is reject
    async function testError(){
         // throw new Error( 'Something went wrong~~' );
          await Promise.reject( 'Something went wrong' );// A return before await has the same effect as no return
    }
    testError()
         // .then ( () = > {}, (error) => { console .log(error);})
         .catch (error=>{ console .log (error);})
    //Error: something went wrong~~

    3. Principle 3

    The await command is followed by a Promise object that returns the result of that object. If it is not a Promise object, it returns the corresponding value directly. Code description:

    // await
    async function getName () {
          // return 'you from the stars';
         return await 'you from the stars' ; // the direct return above is equivalent to this return
    }
    getName()
         .then( result => { console .log(result);})
      //you from the stars

    4. Principle 4

    The use of await requires async. This is the romance of async-await: async returns a Promise object, and await waits for this Promise object, so await cannot be without async (but async can be without await). Have you been romanticized? I'm drunk anyway. What if await doesn't have async? Error:

    // await without async will report an error
    function testAwait () {
          return await 'tomato fried peppers'
    }
    testAwait()
         .catch( error => {
              console.log(error);
         })
    //SyntaxError: await is only valid in async function

    2. In-depth Async-await rules

    1. async encapsulates Promise

    // async wraps Promise
    async function fn1 () {
          return 'Pleasant Goat and Big Big Wolf' ; // //equivalent to return Promise.resolve('Pleasant Goat and Big Big Big Wolf')
         const data = await fn1(); //Receive data value
    }
    fn1() //Execute the async function and return a Promise
         object.then( data => {
              console .log( 'content =' , data)
         })
    
    //content = Pleasant Goat and Big Big Wolf

    2. await is equivalent to then

    // await---.then()
    async function getName () {
          const operate= Promise .resolve( 'Snow White' ) //Execution function
         const name= await operate //await is equivalent to Promise's then operate.then(name=>{})
         console .log( 'name:' , name)
    }
    getName();
    ( async function () {
          const person= await 'seven dwarfs' //await Promise.resolve('seven dwarfs') await is not followed by Promise, it will also be encapsulated as Promise
         console .log( 'person:' ,person) //400
    })(); //Self-executing function
    
    //name: Snow White
    //person: The Seven Dwarfs

    3. When there are multiple awaits, execute in sequence

    When the function is executed, once it encounters await, it will return first, wait until the asynchronous operation is completed, and then execute the statement behind the function body. If the Promise object after any await statement changes to the reject state, the entire async function will be interrupted.

    async function testOrder () {
       await Promise .reject( 'error' ) //UnhandledPromiseRejectionWarning: error
       await Promise .resolve( 'hello world' ); // will not execute
    }
    testOrder();

    4. try…catch is equivalent to catch

    If you want to not interrupt subsequent async operations even if the previous one fails. The first await can be placed inside a try...catch structure, so that the second await will be executed regardless of whether the asynchronous operation succeeds or not.

    // try...catch
    !( async function () {
          const testError = Promise .reject( 'Something went wrong~~~' ) //rejected status
         // const testError=throw new Error('Something went wrong~~~');
         try {
              const result = await testError; //await Equivalent to then, but reject will not trigger then
             console .log( 'success:' +result) //No output, because const result = await testError is reported and caught by catch
         } catch (error) {
              console .error( ' error:' +error) //try...catch is equivalent to Promise's catch
         }
    
    })()
    //error: something went wrong~~~

    When await is followed by a Promise object, we can also directly .catch the error directly after await:

    async function testError () {
          await Promise .reject( 'Something went wrong' )
             .catch( error => console .log(error)); // catch the error here, it will not affect the next await execution
        
         return await Promise .resolve( 'hello world' );
    }
    
    testError()
         .then( result => console .log(result))

    3. Parse Async-await syntax

    Let's take a brief look at an interview question:

    // interview question
    function getJSON () {
          return new Promise ( ( resolve, reject ) => {
             setTimeout( () => {
                  console.log( 2 );
                 resolve(2)
             }, 2000 )
         })
    }
    async function testAsync () {
          await getJSON()
          console.log(3);
    }
    testAsync()
    //2 
    //3

    Of course, the question will not ask about the printing order. The question is to parse and translate the async await statement into a Promise?

    According to the current knowledge, we must know:

    (1) await cannot appear alone, and there must be async in front of its function.

    (2) await will do two things:

    First, put the code written behind await into the Promise created by async to execute.

    Second, put the code written under await into the .then of the previously created Promise object for execution.

    (3) what await returns is also a Promise object, he just puts the code below await into the .then of the promise returned by await and executes it.

    In this case, is it like a duck to water? The translation is as follows:

    function getJSON () {
          return new Promise ( ( resolve, reject ) => {
             setTimeout( () => {
                  console.log( 2 );
                 resolve(2)
             }, 2000 )
         })
    }
    // Compile into Promise principle
    function testAsync () {
          return Promise .resolve().then( () => {
              return getJSON();
         })
             .then( () => {
                  console.log(3);
    
             })
    }
    testAsync()

    Fourth, expand Async-await applications

    1. Scene 1

    Have you learned about async-await? Remember the callback hell at the beginning of the last article? We resolve the callback via Promise like this:

    // Promise solution
    function doCallback ( n ) {
         var myPromise = new Promise ( function ( resolve, reject ) {
             // handle asynchronous tasks
            var flag = true ;
            setTimeout( function () {
                 if (flag) {
                    resolve(n)
                }
                else {
                    reject( 'failed' )
                }
            }, 0 )
        })
        return myPromise;
    }
    
    doCallback(1)
        .then( ( result ) => { //then is a method that is successfully executed and returns a Promise object
            console .log(result); //printing Zhang San res is to execute
            return fn( 2 );
        })
        .then( ( result ) => {
             console.log(result);
             return fn(3)
        })
        .then( ( result ) => {
             console.log(result);
             return fn( 4 )
        })
        .then( ( result ) => {
             console.log(result);
        })
        .catch( ( result ) => { //catch is the method of failed execution
            console.log(result);
        })
        //A lot of .then, forming a .then chain
    //1 
    //2 
    //3
    //4

    Through the above Promise method, the exaggerated performance of "shifting to the right" of callback hell can be obviously solved. However, Promise is based on the chain call of then and catch, but it is also based on the callback function. The .then chain is more or less against the native code, and it is not very elegant. As the ultimate weapon of callback, async-await is closer to native code, let's take a look:

    //Encapsulate an asynchronous task
    function that returns a promise doCallback ( str ) {
         var myPromise = new Promise ( function ( resolve, reject ) {
             var flag = true ;
            setTimeout( function () {
                 if (flag) {
                    resolve(str)
                } else {
                    reject( 'processing failed' )
                }
            })
        })
        return myPromise;
    }
    
    //Encapsulate an async function that performs the above asynchronous task
    async function testAsync () {
         var result1 = await doCallback( 1 ); //await directly gets the promise data returned by fn() and assigns it to result
        var result2 = await doCallback( 2 ); //the code behind await can be seen as is the content of the asynchronous callback callback, all asynchronous
        var result3 = await doCallback( 3 );
         var result4 = await doCallback( 4 );
         console.log(result1);
         console.log(result2);
         console.log(result3);
         console.log( result4 );
    } //Is this more concise and elegant?
    // execute function
    testAsync();
    //1 
    //2 
    //3
    //4

    The above is all the content of the article "async-await eliminates asynchronous callbacks", thank you for reading! I believe that everyone will gain a lot after reading this article. The editor will update different knowledge for you every day. 


    Tags

    Technical otaku

    Sought technology together

    Related Topic

    0 Comments

    Leave a Reply

    +