ReasonML 是否支持 async/await?

Does ReasonML support async/await?

我一直在经历 JS -> Reason cheatsheet on the Reason ML website。它们非常有用,但是 none 涵盖了现代 ES 中可用的 async/await 语法。

Reason ML 等同于什么?

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

ReasonML documentation 说:

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

也就是说目前不支持async/await.

如果您喜欢 ReasonML 但想要异步功能,请查看 OCaml。 They have a few syntax differences 但在其他方面非常相似。 Reason 甚至使用了 OCaml 的编译器,而且基本上是 OCaml 加上大括号,让 Javascript 开发者不那么害怕。 OCaml 使用了两个异步库:Lwt and Jane Street's Async.

目前(2018 年 10 月)"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 支持异步语法,如下所示:

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)
};