2
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)

Why is it that in the code above, specifically

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

that the return returns Promise pending, even though the line above it has the right result? And how could I change this so that it does?

Thanks in advance and sorry for the badly written question... (Writing well formulated SO questions is not one of my strong points)

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Yamboy1
  • 23
  • 4
  • Can you add this as an answer please – Yamboy1 Apr 29 '18 at 07:44
  • @CertainPerformance please do not answer questions in comments. Not taking the time to reply makes someone replying look like they copied your comment - as if they didn't know the answer to the question anyway! – traktor Apr 29 '18 at 07:52
  • @traktor53 Ok, I turned it into an answer. I noticed that others often answer tiny questions in comments, and when I post a real answer (to trivial but non-typo questions) rather than a comment, it sometimes attracts downvotes. – CertainPerformance Apr 29 '18 at 08:26
  • @CertainPerformance Thanks for posting the answer. Some others are known for answering in comments but are too elderly to correct :-) Attracting a downvote has its own criteria of risk - a downvote may suggest the answer could be imporved! – traktor Apr 29 '18 at 08:44

1 Answers1

2

async functions always return promises (even if their operations are completely synchronous). You have to call .then on the result of the call.

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

Note that you can't just consume it with something like

const game = await buildMap();

because you can't await on the top level - you can only await inside of an async function.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • oh, thanks, I missed the point on "top-level `await`". I've googled pretty article around this thing: https://gist.github.com/Rich-Harris/0b6f317657f5167663b493c722647221 – skyboyer Apr 29 '18 at 09:10