Created
October 19, 2025 11:18
-
-
Save i5ting/61f7e3046955a63d33e19383fb66e103 to your computer and use it in GitHub Desktop.
moonbit async初体验,先写个文件
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 听说moonbit支持async了,这是我一直以来最期待的特性,有了async才是真正的让普通程序员也可以做应用落地,于是想简单的尝试一下,顺便做个备忘。 | |
| - 今日目标:完成文件写入 | |
| 首先是新建模块 | |
| ```jsx | |
| $ moon new async-helloworld | |
| ``` | |
| 这时候目录下面会有async-helloworld.mbt,其实我不喜欢这种写法,不如直接用index.mbt更好理解。 | |
| async模块只支持native,所以首先要在moon.mod.json文件里设置target是native,不然无法变异。 | |
| ```jsx | |
| "preferred-target": "native", | |
| ``` | |
| 然后需要解决模块registry更新的问题。 | |
| ```jsx | |
| $ moon update | |
| ``` | |
| 更新完成后,我们需要增加async模块 | |
| ```jsx | |
| $ moon add moonbitlang/async@0.10.0 | |
| ``` | |
| 此时它会在moon.mod.json配置里增加deps | |
| ```jsx | |
| "deps": { | |
| "moonbitlang/async": "0.10.0" | |
| }, | |
| ``` | |
| 然后为了测试方便,我们在cmd/main/main.mbt里修改代码 | |
| ```jsx | |
| ///| | |
| async fn main { | |
| @lib.write_file() | |
| } | |
| ``` | |
| 主要是给main增加async关键字,有了async它内部才能调用async function。为了能够让main运行,我们需要修改它里面的moon.pkg.json,增加async模块的import。 | |
| ```jsx | |
| { | |
| "is-main": true, | |
| "import": [ | |
| { | |
| "path": "username/doc", | |
| "alias": "lib" | |
| }, | |
| { | |
| "path": "moonbitlang/async" | |
| } | |
| ] | |
| } | |
| ``` | |
| 准备好main之后,我们就需要在async-helloworld.mbt里添加write_file方法了。 | |
| ```jsx | |
| pub async fn write_file() -> Unit { | |
| let test_file = "test_read_file.txt" | |
| @fs.write_file(test_file, b"Hello, MoonBit!", create=0o644) | |
| let content = @fs.read_file(test_file) | |
| // @fs.remove(test_file) | |
| inspect(content.text(), content="Hello, MoonBit!") | |
| } | |
| ``` | |
| 为了能够让write_file方法不报错,也是需要在在moon.pkg.json文件中,修改import | |
| ```jsx | |
| { | |
| "import": [ | |
| { | |
| "path": "moonbitlang/async/fs", | |
| "alias": "fs" | |
| }, | |
| { | |
| "path": "moonbitlang/async/io" | |
| // "alias": "io" | |
| } | |
| ] | |
| } | |
| ``` | |
| 需要注意的是,fs以来io模块,这是因为content.text()返回的类型是io.Data,所以你也需要把io模块引入,由于代码中没有使用@io这个alias,所以不能加上alias,否则会有warning。 | |
| 至此,我们执行如下命令就可以创建文件了。 | |
| ```jsx | |
| $ moon run cmd/main | |
| ``` | |
| 这时候在项目根目录,就会test_read_file.txt文件,里面内容是"Hello, MoonBit!"。 | |
| 总结一下,整个过程还是还是比较简单的,有几个点需要注意 | |
| 1、moonbit是支持多端编译的,默认是wasm,如果使用async,就只能native,理解上会麻烦一点。 | |
| 2、moonbit的import是配置式的,这时候就会很麻烦,你需要同时关注moon.mod.json和moon.okg.json,里面的约定配置部分还是非常多的。 | |
| 3、对于普通函数和async函数调用,简化了await关键字。唯一麻烦的就是main上,你也需要加上async的import,这让我觉得不是很舒服。 | |
| 以上。 | |
| 参考 | |
| - async官方博客 https://www.moonbitlang.com/blog/moonbit-async#what-is-asynchronous-programming | |
| - 源码https://github.com/moonbitlang/async | |
| - 文档 https://mooncakes.io/docs/moonbitlang/async/fs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment