协程
# Hello Word
hello.txt
```js
Nothing
```
main.js
```js
// 注意,要使用协程这个特性,必须使用项目功能,并且在project.json配置好features属性
// delay不同于sleep,不会阻塞当前线程
function delay(millis) {
var cont = continuation.create();
setTimeout(()=>{
cont.resume();
}, millis);
cont.await();
}
// 异步IO例子,在另一个线程读取文件,读取完成后返回当前线程继续执行
function read(path) {
var cont = continuation.create();
threads.start(function(){
try {
cont.resume(files.read(path));
}catch(err){
cont.resumeError(err);
}
});
return cont.await();
}
// 使用Promise和协程的例子
function add(a, b) {
return new Promise(function(resolve, reject) {
var sum = a + b;
resolve(sum);
});
}
toastLog("Hello, Continuation!");
//3秒后发出提示
setTimeout(()=>{
toastLog("3秒后....");
}, 3000);
// 你可以尝试把delay更换成sleep,看会发生什么!
delay(6000);
toastLog("6秒后...");
try {
toastLog("读取文件hello.txt: " + read("./hello.txt"));
}catch(err){
console.error(err);
}
var sum = add(1, 2).await();
toastLog("1 + 2 = " + sum);
```
project.json
```json
{
"name": "协程HelloWorld",
"main": "main.js",
"ignore": [
"build"
],
"packageName": "com.example.cont.helloworld",
"versionName": "1.0.0",
"versionCode": 1,
"useFeatures": ["continuation"]
}
```
# UI例子
main.js
```js
"ui";
ui.layout(
<frame bg="#4fc3f7">
<text textColor="white" textSize="18sp" layout_gravity="center">
UI中使用协程
</text>
</frame>
);
continuation.delay(5000);
if (!requestScreenCapture()) {
dialogs.alert("请授予软件截图权限").await();
}
// 退出应用对话框
ui.emitter.on("back_pressed", function (e) {
e.consumed = true;
let exit = dialogs.confirm("确定要退出程序").await();
if (exit) {
ui.finish();
}
});
```
project.json
```json
{
"name": "协程UI示例",
"main": "main.js",
"ignore": [
"build"
],
"packageName": "com.example.cont.ui",
"versionName": "1.0.0",
"versionCode": 1,
"useFeatures": ["continuation"]
}
```