增加 可选特性continuation

增加 协程示例
This commit is contained in:
hyb1996
2018-12-12 17:31:48 +08:00
parent 7e7a7556e8
commit 975940dced
23 changed files with 450 additions and 261 deletions

View File

@@ -0,0 +1,24 @@
"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();
}
});

View File

@@ -0,0 +1,11 @@
{
"name": "协程UI示例",
"main": "main.js",
"ignore": [
"build"
],
"packageName": "com.example.cont.ui",
"versionName": "1.0.0",
"versionCode": 1,
"useFeatures": ["continuation"]
}

View File

@@ -0,0 +1 @@
Nothing

View File

@@ -0,0 +1,54 @@
// 注意要使用协程这个特性必须使用项目功能并且在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);

View File

@@ -0,0 +1,11 @@
{
"name": "协程HelloWorld",
"main": "main.js",
"ignore": [
"build"
],
"packageName": "com.example.cont.helloworld",
"versionName": "1.0.0",
"versionCode": 1,
"useFeatures": ["continuation"]
}