js asynchronous to synchronous

Posted by JamesU2002 on Thu, 16 May 2019 12:43:35 +0200

There is some logic in the project or requests depend on another asynchronous request, and the common method is the callback function.Now there's a big solution: await async.

Async is short for async, while await can be considered short for async wait.It should therefore be well understood that async is used to declare that a function is asynchronous, while await is used to wait for an asynchronous method to execute.And await can only appear in the async function, otherwise an error will be reported.

async action:

When an async function is called, a Promise Object.When this async function returns a value, Promise's resolve method is responsible for passing the value; when the async function throws an exception, Promise's reject method also passes the exception.

There may be await Expression, which causes the async function to pause execution, wait for the result of Promise, then resume execution of the async function and return the resolved value.

await effect:

The await expression pauses the current async function Execution, waiting for Promise processing to complete.If Promise is fulfilled, its callback resolve function parameter continues execution as the value of the await expression. async function.

If Promise handles rejected exceptions, the await expression throws the cause of Promise's exceptions.In addition, if the value of the expression after the await operator is not a Promise, the value itself is returned.

For a chestnut:

     function resolveAfter2Seconds() {
        return new Promise(resolve => {
          setTimeout(() => {
            resolve('resolved');
          }, 2000);
        });
      }

      async function asyncCall() {
        console.log('calling1');
        var result = await resolveAfter2Seconds();
        console.log(result);
        console.log('calling2');
        // expected output: 'calling1','resolved','calling2'
      }

      asyncCall();

Combined with reality:

    function getData() {
        return  axios.get('/url')
      }
      async function asyncCall() {
        var {data} = await getData();
        console.log(data)
      }
      asyncCall();

Notes:

function getData1() {
        console.log(new Date())
        return new Promise(resolve => {
          setTimeout(() => {
            resolve('resolved');
          }, 2000);
        });
      }
      function getData2() {
        console.log(new Date())
        return new Promise(resolve => {
          setTimeout(() => {
            resolve('resolved2');
          }, 2000);
        });
      }
      async function asyncCall() {
        var data1 = await getData1();
        var data2 = await getData2();
        console.log(data1)
        console.log(data2)
      }
      asyncCall();

Result:

Mon Apr 29 2019 14:42:14 GMT+0800 (China Standard Time)
Mon Apr 29 2019 14:42:16 GMT+0800 (China Standard Time)
 resolved
 resolved2

It can be seen that getData2 does not execute until getData1 has finished executing, which can cause a waste of time if getData2 does not depend on the return value of getData1.You can change to the following:

  function getData1() {
        console.log(new Date())
        return new Promise(resolve => {
          setTimeout(() => {
            resolve('resolved');
          }, 2000);
        });
      }
      function getData2() {
        console.log(new Date())
        return new Promise(resolve => {
          setTimeout(() => {
            resolve('resolved2');
          }, 2000);
        });
      }
      async function asyncCall() {
        var data1 =  getData1();
        var data2 =  getData2();
        data1 = await data1
        data2 = await data2
        console.log(data1)
        console.log(data2)
      }
      asyncCall();

Result:

Mon Apr 29 2019 14:51:52 GMT+0800 (China Standard Time)
Mon Apr 29 2019 14:51:52 GMT+0800 (China Standard Time)

resolved
resolved2

Topics: Javascript axios