【问题标题】:ASYNC / AWAIT SyntaxError: await is only valid in async functions and the top level bodies of modulesASYNC / AWAIT SyntaxError: await 仅在异步函数和模块的顶层主体中有效
【发布时间】:2021-11-04 10:11:50
【问题描述】:

我正在做一些关于使用csvtojson node module 将 csv 文件读取为 json 格式的非常简单的测试,我使用下面的代码作为模板

a,b,c
1,2,3
4,5,6
*/
const csvFilePath='<path to csv file>'
const csv=require('csvtojson')
csv()
.fromFile(csvFilePath)
.then((jsonObj)=>{
    console.log(jsonObj);
    /**
     * [
     *  {a:"1", b:"2", c:"3"},
     *  {a:"4", b:"5". c:"6"}
     * ]
     */ 
})
 
// Async / await usage
const jsonArray=await csv().fromFile(csvFilePath);

我主要关注的是

// 异步/等待使用

const jsonArray=await csv().fromFile(csvFilePath);

代码部分。对了,这是我的代码

// const JSONtoCSV = require("json2csv")
// const FileSystem = require("fs")

async function test()
{
    const data = await CSVtoJSON().fromFile('./input.csv')
    return data
}

let temp = await test()

console.log(temp)

无论我尝试过哪种方式,我总是收到以下错误

let temp = await test()
           ^^^^^

SyntaxError: await is only valid in async functions and the top level bodies of modules
    at Object.compileFunction (node:vm:352:18)
    at wrapSafe (node:internal/modules/cjs/loader:1031:15)
    at Module._compile (node:internal/modules/cjs/loader:1065:27)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12)
    at node:internal/main/run_main_module:17:47

const data = await CSVtoJSON().fromFile('./input.csv');
             ^^^^^

SyntaxError: await is only valid in async functions and the top level bodies of modules
    at Object.compileFunction (node:vm:352:18)
    at wrapSafe (node:internal/modules/cjs/loader:1031:15)
    at Module._compile (node:internal/modules/cjs/loader:1065:27)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12)
    at node:internal/main/run_main_module:17:47

如果我像这样将代码切换为顶级

const CSVtoJSON = require("csvtojson")
// const JSONtoCSV = require("json2csv")
// const FileSystem = require("fs")

const data = await CSVtoJSON().fromFile('./input.csv')

console.log(data)

我不明白为什么这不起作用。

编辑:我按照@tasobu 的说明进行了更改。现在我得到的只是一个返回的承诺

const data = (async () => {
    return await CSVtoJSON().fromFile('./input.csv')
})

console.log(data)
Debugger attached.
Promise { <pending> }
Waiting for the debugger to disconnect...

【问题讨论】:

  • 错误信息很清楚:你的代码是模块吗?你的awaitasync 函数内吗?如果答案是“否”,那就是问题所在。
  • 为什么csvtojson提供的是JS对象,而不是json?
  • 只能在异步函数中使用 await。您已经在 let temp = await test() 中使用了它
  • 正如 Invizi 所说,将 let temp = await test() 替换为 let temp = test()

标签: javascript node.js asynchronous async-await


【解决方案1】:

Promise在未来会返回一些东西,所以你需要一种等待它的方法。

// const CSVtoJSON = require("json2csv")
// const FileSystem = require("fs")
let temp = undefined;

async function test()
{
    const data = await CSVtoJSON().fromFile('./input.csv')
    // do your stuff with data
    
    temp = data;

    console.log(temp) // at this point you have something in.
    return true
}

test();
console.log(temp) // at this point nothing was there.

【讨论】:

  • 谢谢你。我知道这里的许多答案是相同的,并提供相同的解决方案,这个答案为我提供了让我更好地理解这一点的细节。
【解决方案2】:

将你的整个代码放入一个异步函数并调用它,所以除了一些const 语句和函数之外的函数/类声明之外你不会有任何东西:

async function main () {
  // All code here, can use await
}

main().then(() => process.exit(0), e => { console.error(e); process.exit(1) })

【讨论】:

    【解决方案3】:

    您可以在此处使用 IIFE(了解更多信息 here

    (async function main () {
        // You can use await inside this function block
    })();
    

    【讨论】:

      【解决方案4】:

      如果您不想使用 await 部分,则必须省略它。

      const csvFilePath = "./data.csv"
      const csv = require("csvtojson")
      csv()
        .fromFile(csvFilePath)
        .then((jsonObj) => {
          console.log(jsonObj)
        })
      
      // Async / await usage
      //const jsonArray = await csv().fromFile(csvFilePath)
      

      或者:

      // Async / await usage
      async function csvToJson() {
        const res = await csv().fromFile(csvFilePath)
        console.log(res)
      }
      
      csvToJson()
      

      【讨论】:

      • 我实际上更喜欢使用 ASYNC AWAIT 部分。我真的不喜欢数英里的 .then().then().then 语句。此外,我希望能够获取 csv 文件的结果,然后在以后的代码迭代中多次使用它
      • 投反对票不太好,但我为你写(编辑)了异步。
      • 人们可以根据自己的想法和意愿投票赞成或反对,这没有什么不好,这就是网站的运作方式。顺便说一句,如果任何事情失败,您的解决方案将导致未处理的承诺拒绝,最好指出在从非异步上下文调用异步函数时需要.catch
      • 我只是重写了模板代码...(没有“.catch”)...我的两个解决方案都得到了正确的结果...谢谢你让我了解投票系统我仍然认为这不公平,但我已经习惯了。
      猜你喜欢
      • 1970-01-01
      • 2022-06-22
      • 1970-01-01
      • 2022-01-17
      • 2020-09-11
      • 1970-01-01
      • 1970-01-01
      • 2020-12-07
      • 2020-02-11
      相关资源
      最近更新 更多