4

I have been going through the JS -> Reason cheatsheet on the Reason ML website. They are very helpful, but none cover the async/await syntax available in modern ES.

What is the Reason ML equivalent of this?

import fs from 'mz/fs';

// A cat-like utility
const main = async () => {
  if (process.argv.length != 3) {
    throw new Error('Expected a file-path');
  }
  const path = process.argv[2];
  const content = await fs.readFile(path);
  console.log(content.toString());
};

main().catch(error => console.error(error));
glennsl
  • 28,186
  • 12
  • 57
  • 75
sdgfsdh
  • 33,689
  • 26
  • 132
  • 245

3 Answers3

4

ReasonML documentation says:

Note: we might offer a dedicated syntax for JS promises (async/await) in the future.

Which means it doesn't currently support async/await.

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
  • 1
    What a shame! This makes Reason significantly less appealing than, say, F# + Fable. – sdgfsdh Feb 15 '18 at 17:09
  • Almost 3 years later you can still not use async-await with reasonml because BuckleScript does not yet support it. You can use bs-let as mentioned in a comment of the question but the repo warns that the generated code is not very performant. I was looking for a type-safe way to write react code. Now Feliz, which is based on F# and Fable looks most promising (see https://github.com/Zaid-Ajaj/Feliz). – David Dec 01 '20 at 19:14
2

There is currently (October 2018) a "Syntax proposal: async/await" Pull Request open to implement this that's been open for about 15 months now. At the end of last year one of the developers wrote a blog post about their plans and noting some of the problems of handling some of the JavaScript Promise quirks. From the blog post there is even an example Github repo with support for async syntax that looks like this:

let getThing = () => Js.Promise.make((~resolve, ~reject) => [@bs]resolve(20));
let getOtherThing = () => Js.Promise.make((~resolve, ~reject) => [@bs]resolve(40));

let module Let_syntax = Reason_async.Promise;
let doSomething = () => {
  /* These two will be awaited concurrently (with Promise.all) */
  [%await let x = Js.Promise.resolve(10)
  and y = getThing()];

  [%awaitWrap let z = getOtherThing()];
  x + y + z + 3
};

/* Heyy look we have top-level await!
 * `consume` means "give me this promise, and have the result
 * of this whole expression be ()" */
{
  [%consume let result = doSomething()];
  Js.log(result)
};
icc97
  • 11,395
  • 8
  • 76
  • 90
1

If you like ReasonML but want async functionality, check out OCaml. They have a few syntax differences but are otherwise very similar. Reason even uses OCaml's compiler, and is basically OCaml with braces to make Javascript developers less afraid. OCaml has two async libraries in use: Lwt and Jane Street's Async.

Chris S
  • 21
  • 7