一尘不染

等待仅在异步功能中有效

node.js

我写了这段代码 lib/helper.js

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

然后我尝试在另一个文件中使用它

 var helper = require('./helper.js');   
 var start = function(a,b){
     ....
     const result = await helper.myfunction('test','test');
 }
 exports.start = start;

我有一个错误

“等待仅在异步功能中有效”

有什么问题


阅读 361

收藏
2020-07-07

共1个答案

一尘不染

错误不是指myfunction而是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();


我利用这个问题的机会来告诉你一个已知的反模式的使用await方法:return await


错误

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');

})();

正确

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');

})();

另外,要知道有一个return await正确且重要的特殊情况:(使用try / catch)

2020-07-07