1

I have a Javascript async/await design question.

Imagine this function exists:

async function readFile(filename) { 
   // Asynchronously reads file and returns the content as string
}

Now if I were to use readFile with a certain parameter and return its result, I could do it either like so:

async function readSettings1() {
   const settings = await readFile("settings.json");
   return settings;
}

or:

async function readSettings2() {
   return readFile("settings.json");
}

I understand both approaches work similarly, and must be invoked identically. They both return Promises. There are a couple of syntactic differences:

  1. readSettings1 first resolves the value of readFile and then returns the hard result. Here, the keyword async is used in the function definition so I can use await.

  2. readSettings2 is really just a passthrough. In fact, I can omit async from this function definition.

My question is: are there any semantic differences between readSettings1 and readSettings2? Do they behave differently in any way? Do you have a preference for either style? Why? Have you read any documentation recommending one style over the other?

Arash Motamedi
  • 9,284
  • 5
  • 34
  • 43
  • https://babeljs.io/repl#?babili=false&browsers=&build=&builtIns=false&code_lz=IYZwngdgxgBAZgV2gFwJYHsIwLYAoCUMA3gL4BQZoksiKGWAHgcTAE4CmyCrWeh5ZWlDSYYYZkTaduvZiSA&debug=false&circleciRepo=&evaluate=false&lineWrap=true&presets=es2015%2Creact%2Cstage-2&prettier=false&targets=&version=6.26.0 – Andrew Li Dec 15 '17 at 22:34
  • 2
    Yes, I would recommend to omit even the `async` from `readSettings2`. Alternatively use partial application: `const readSettings = readFile.bind(null, "settings.json");` – Bergi Dec 15 '17 at 22:44
  • @Bergi Thanks! Your answer is great: https://stackoverflow.com/a/43985067/417866 – Arash Motamedi Dec 15 '17 at 23:35
  • @Bergi Would you please care to direct me to some place where I can understand that `.bind(null, ...)` syntax/method? Is your suggestion different from `const readSettings = () => readFile("settings.json")`? – Arash Motamedi Dec 15 '17 at 23:39
  • @ArashMotamedi It's basically the same. One can use [`bind`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) for [partial application](https://en.wikipedia.org/wiki/Partial_application). – Bergi Dec 15 '17 at 23:54

0 Answers0