【问题标题】:Async/Await is only valid async func while reading a file [duplicate]异步/等待仅在读取文件时才是有效的异步函数[重复]
【发布时间】:2019-07-02 16:58:59
【问题描述】:

我试图使用 Async/Await 读取 JSON 文件,我创建了基于 Native async/await approach 的示例,但出现此错误。

SyntaxError: await 仅在异步函数中有效

这是我的代码。

const fs = require('fs-extra');
const xml2js = require('xml2js');  
const parser = new xml2js.Parser();

const path = "file.json";

function parseJM() {
return new Promise(function (resolve, reject) {
    fs.readFile(path, { encoding: 'utf-8'}, (err, data) => {
        if (err) { reject(err); }
        else {
            resolve (parser.parseString(data.replace(/<ent_seq>[0-9]*<\/ent_seq>/g, "")
             .replace(/&(?!(?:apos|quot|[gl]t|amp);|#)/g, '')));
        }
    });
});
}

const var1 = await parseJM();
console.log(var1);

我的代码有什么问题?我的 node 版本是 11.9.0,我的 npm 版本是 6.7.0,我使用的是 Arch Linux。

【问题讨论】:

  • 我的代码有什么问题? ---> await 仅在 async 函数中有效,就像您已经在问题中回答一样
  • 错误告诉你代码到底出了什么问题。
  • 你在这里使用fs-extra,所以不要打扰使用new Promise..All fs methods return promises if the callback isn't passed.
  • 这样写的目的,promise本身是不够的。
  • 我不明白为什么这个社区对人们如此苛刻

标签: javascript node.js asynchronous


【解决方案1】:

您需要在异步函数中调用 await。

(async () => {
    try {
        const var1 = await parseJM();
        console.log(var1);
    } catch (e) {
        console.error(e.message);
    }
})();

编辑:正如@Nik Kyriakides 所建议的那样

【讨论】:

  • try/catch 在您执行此操作时是必须的。否则你会为自己犯下的错误做好准备。
  • 不使用IFFE是否可行
  • @KaanTahaKöken 是的,您可以使用.then/resolve,因为async 标记的函数返回Promise
  • @NikKyriakides 没有完全吞下。如果在 parseJM() 调用中抛出错误,您将得到 "unhandledRejection"
  • @Aikei 不错,用词不当。
【解决方案2】:

错误本身可以准确地告诉您问题所在。您只能在 async 标记的函数中使用 await

如果这是您的顶级代码,您可以使用 async IIFE

;(async () => {
  try {
    await doSomething()  
  } catch (err) {
    console.error(err)
  }
})()

或者只是then/catch它。 async 函数毕竟返回 Promise

doSomething() 
  .then(result => {
    console.log(result)
  })
  .catch(err => {
    console.error(err)
  })

【讨论】:

  • 为什么是;?是错字还是我不知道的巧妙技巧?
  • 只是为了确保你不会陷入this trap
  • 这就是当您不始终使用分号时代码的外观。不是我的菜。
  • 除了 IIFE,我从来没有必须在任何东西前面加上 ;。我的看法是,没有它们会好得多。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-11
  • 2019-07-15
  • 1970-01-01
  • 2022-01-25
  • 1970-01-01
  • 2021-01-14
  • 1970-01-01
相关资源
最近更新 更多