await is only valid in async function

后端 未结 9 1585
青春惊慌失措
青春惊慌失措 2020-11-22 06:53

I wrote this code in lib/helper.js

var myfunction = async function(x,y) {
   ....
   return [variableA, variableB]
}
exports.myfunction = myfunct         


        
9条回答
  •  执念已碎
    2020-11-22 07:30

    The error is not refering to myfunction but to start.

    async function start() {
       ....
    
       const result = await helper.myfunction('test', 'test');
    }
    

    // My function
    const myfunction = async function(x, y) {
      return [
        x,
        y,
      ];
    }
    
    // Start function
    const start = async function(a, b) {
      const result = await myfunction('test', 'test');
      
      console.log(result);
    }
    
    // Call start
    start();



    I use the opportunity of this question to advise you about an known anti pattern using await which is : return await.


    WRONG

    async function myfunction() {
      console.log('Inside of myfunction');
    }
    
    // Here we wait for the myfunction to finish
    // and then returns a promise that'll be waited for aswell
    // It's useless to wait the myfunction to finish before to return
    // we can simply returns a promise that will be resolved later
    
    // useless async here
    async function start() {
      // useless await here
      return await myfunction();
    }
    
    // Call start
    (async() => {
      console.log('before start');
    
      await start();
      
      console.log('after start');
    })();


    CORRECT

    async function myfunction() {
      console.log('Inside of myfunction');
    }
    
    // Here we wait for the myfunction to finish
    // and then returns a promise that'll be waited for aswell
    // It's useless to wait the myfunction to finish before to return
    // we can simply returns a promise that will be resolved later
    
    // Also point that we don't use async keyword on the function because
    // we can simply returns the promise returned by myfunction
    function start() {
      return myfunction();
    }
    
    // Call start
    (async() => {
      console.log('before start');
    
      await start();
      
      console.log('after start');
    })();


    Also, know that there is a special case where return await is correct and important : (using try/catch)

    Are there performance concerns with `return await`?

提交回复
热议问题