如何通过promise/async-await返回Papa解析的CSV

mth*_*m85 0 javascript promise async-await papaparse

有人能帮我理解为什么这会返回一个挂起的承诺,而不是数据吗?

async function toJson (filepath) {
  const file = fs.createReadStream(filepath)
  let json = new Promise((resolve, reject) => {
    Papa.parse(file, {
      header: true,
      complete (results, file) {
        resolve(results)
      },
      error (err, file) {
        reject(err)
      }
    })
  })
  let result = await json
  return result.data
}
Run Code Online (Sandbox Code Playgroud)

如果我将return result.data行更改为console.log(result.data),它会按预期将数据数组记录到控制台。为什么它不简单地返回那个数组?!?!

Asa*_*viv 8

正如 Roamer-1888 在评论中添加的那样,异步函数总是返回一个Promise,即使你await在它里面然后返回数据,它也会作为一个 Promise 返回。

在函数的调用者中,您必须等待 Promise 或使用.then()它才能访问传递的数据。

toJson函数可以更好地编写为仅返回这样的 Promise

function toJson (filepath) {
  const file = fs.createReadStream(filepath)
  return new Promise((resolve, reject) => {
    Papa.parse(file, {
      header: true,
      complete (results, file) {
        resolve(results.data)
      },
      error (err, file) {
        reject(err)
      }
    })
  })
}
Run Code Online (Sandbox Code Playgroud)

现在,当您调用 时toJson(),您可以使用await异步函数或.then()返回的 Promise链来访问数据。

async function main() {
  try {
    const data = await toJson(filepath)
    // do something with the data...
  } catch (err) {
    console.error('Could not parse json', err)
  }
}
Run Code Online (Sandbox Code Playgroud)

或与 .then()

toJson('path')
.then(console.log)
.catch(console.log)
Run Code Online (Sandbox Code Playgroud)

您将能够从底层FileReader 中捕获错误(感谢rejecterror函数内部调用)。请记住,通过调用resolveresults.data您放在一边results.errorsresults.meta包含有关读取 csv 的有用信息。