async await not working properly

前端 未结 3 2077
南方客
南方客 2021-01-29 05:32

I am new to JavasSript\'s async, await and promise features.

What I am doing is,

async function sendTextMessage(te         


        
3条回答
  •  情书的邮戳
    2021-01-29 05:48

    I hope that all you want todo is process some operations in strict order.

    This is why async and await in ES6 exists.

    So by example it may be like this do A then do B then do C or A > B > C

    As you can see the last method do3 has only 500 ms delay but it is executed as last and not as first one. Without async and await operators it would be executed as first function and this is default behavior of JavaScript execution. Broser will execute sync code as first and async after. But not with async and await anymore :)

    You should also know that if you prefix string, number of function with await then the will be transformed into promise automatically.

    The console will print :

    'juraj1'
    'juraj2'
    'juraj3'

    here is simple example :

    function do1() {
          return new Promise(resolve => {
              return setTimeout(() => resolve("juraj1"), 3000);
       });
     }
    function do2() {
          return new Promise(resolve => {
                return setTimeout(() => resolve("juraj2"), 2000);
      });
     }
    
    function do3() {
          return new Promise(resolve => {
                 return setTimeout(() => resolve("juraj3"), 500);
      });
    }
    
    async function ForceAsynTOBeSync() {
        const a = await do1();
    
        console.log(a);
    
        const b = await do2();
    
        console.log(b);
    
        const c = await do3();
    
        console.log(c);
      }
    
      ForceAsynTOBeSync();
    

提交回复
热议问题