我在lib/helper.js中编写了以下代码:

var myfunction = async function(x,y) {
   ....
   return [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;

我得到一个错误:

await is only valid in async function

问题是什么?


当前回答

如果在foreach中调用了async函数,则将其更新为for循环

其他回答

错误不是指向myfunction,而是指向start。

async function start() {
   ....

   const result = await helper.myfunction('test', 'test');
}

//函数 Const myfunction = async函数(x, y) { 返回( x, y, ]; } //启动函数 Const start = async函数(a, b) { Const result = await myfunction('test', 'test'); console.log(结果); } //调用开始 开始();



我利用这个问题的机会来建议您使用await的一个已知的反模式,即:返回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)

“返回等待”是否存在性能问题?

“await只在异步函数中有效”

但是为什么呢?'await'显式地将异步调用转换为同步调用,因此调用方不能是异步的(或异步的)——至少不是因为调用是在'await'进行的。

在这篇不错的文章中找到下面的代码:使用Axios的Node中的HTTP请求

const axios = require('axios')

const getBreeds = async () => {
  try {
    return await axios.get('https://dog.ceo/api/breeds/list/all')
  } catch (error) {
    console.error(error)
  }
}

const countBreeds = async () => {
  const breeds = await getBreeds()

  if (breeds.data.message) {
    console.log(`Got ${Object.entries(breeds.data.message).length} breeds`)
  }
}

countBreeds()

或者用Promise:

const axios = require('axios')

const getBreeds = () => {
  try {
    return axios.get('https://dog.ceo/api/breeds/list/all')
  } catch (error) {
    console.error(error)
  }
}

const countBreeds = async () => {
  const breeds = getBreeds()
    .then(response => {
      if (response.data.message) {
        console.log(
          `Got ${Object.entries(response.data.message).length} breeds`
        )
      }
    })
    .catch(error => {
      console.log(error)
    })
}

countBreeds()

在以后的nodejs(>=14)中,允许在package中指定{"type": "module"}来执行top await。Json或文件扩展名为.mjs。

https://www.stefanjudis.com/today-i-learned/top-level-await-is-available-in-node-js-modules/

当我得到这个错误时,原来我在我的“async”函数中调用了map函数,所以这个错误消息实际上是指映射函数没有被标记为“async”。我绕过了这个问题,把“await”调用从map函数中取出,并提出了一些获得预期行为的其他方法。

var myfunction = async function(x,y) {
    ....
    someArray.map(someVariable => { // <- This was the function giving the error
        return await someFunction(someVariable);
    });
}