【问题标题】:Return doesn't seem to be awaiting javascriptReturn 似乎没有在等待 javascript
【发布时间】:2018-10-09 14:07:32
【问题描述】:
const fs = require('fs')
const util = require('util')

const readFile = util.promisify(fs.readFile)

const buildMap = async () => {
  let map = await readFile(process.argv[2], { encoding: 'utf-8' })
  console.log(map) // Returns the right result
  return map // Returns `Promise { <pending> }`
}

const game = buildMap()
console.log(game)

为什么在上面的代码中,具体是这样的

let map = await readFile(process.argv[2], { encoding: 'utf-8' })
console.log(map) // Returns the right result
return map // Returns Promise { <pending> }

即使它上面的行有正确的结果,返回返回 Promise 未决?我怎样才能改变它呢?

在此先感谢您对写得不好的问题感到抱歉...(写出格式良好的 SO 问题不是我的强项之一)

【问题讨论】:

  • 你能把这个添加为答案吗
  • @CertainPerformance 请不要在 cmets 中回答问题。不花时间回复会使回复的人看起来像是复制了您的评论 - 就好像他们不知道问题的答案一样!
  • @traktor53 好的,我把它变成了答案。我注意到其他人经常在 cmets 中回答小问题,当我发布一个真正的答案(针对琐碎但非拼写错误的问题)而不是评论时,它有时会吸引反对票。
  • @CertainPerformance 感谢您发布答案。其他一些人以在 cmets 中回答而闻名,但年龄太大而无法纠正 :-) 吸引反对票有其自身的风险标准 - 反对票可能表明答案可能会有所改善!

标签: javascript node.js async-await es6-promise ecmascript-2017


【解决方案1】:

async 函数总是返回承诺(即使它们的操作是完全同步的)。您必须根据通话结果致电.then

buildMap().then((game) => {
  // do stuff with game
  console.log(game);
});

请注意,您不能只用类似的东西来消费它

const game = await buildMap();

因为您不能在顶层 await - 您只能在异步函数内部 await

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-21
  • 1970-01-01
  • 2019-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多