我一直在经历JS -> Reason cheatsheet on the Reason ML website。它们非常有用,但没有一种涵盖现代ES中可用的async
/ await
语法。
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));
答案 0 :(得分:3)
答案 1 :(得分:2)
目前(2018年10月)开放"Syntax proposal: async/await" Pull Request来实施此功能,现已开放约15个月。去年年底,一位开发人员写了blog post关于他们的计划,并指出了处理一些JavaScript Promise怪癖的问题。在博客文章中甚至有一个示例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)
};
答案 2 :(得分:1)
如果您喜欢ReasonML但想要异步功能,请查看OCaml。 They have a few syntax differences,但两者非常相似。 原因甚至使用OCaml的编译器,并且基本上是带括号的OCaml,可以减少Javascript开发人员的恐惧。 OCaml有两个正在使用的异步库:Lwt和Jane Street的Async。