等待仅在异步功能中有效

等待仅在异步功能中有效

我在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;


我有一个错误


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


有什么问题

最佳答案

错误不是引用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');
})();

关于javascript - 等待仅在异步功能中有效,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54896212/

10-11 09:19