Open bronze1man opened 11 years ago
然后我想试试复杂一点的情况,但是不知道如何用windjs完成它....到底哪些地方需要用$await呢? golang代码如下...
package main
import "fmt"
import "time"
//同步转换为异步
func setTimeout(cb func(),timeout int){
go func(){
time.Sleep( time.Duration(int64(timeout)*1e9));
cb();
}()
}
//异步转换为同步
func sleep(timeout int){
c:=make(chan int);
go func(){
setTimeout(func(){
c<-1
},timeout)
}()
<-c
}
func main(){
setTimeout(func(){
fmt.Println("after time out");
},1);
fmt.Println("before sleep");
sleep(2);
fmt.Println("after sleep");
}
想法
模仿golang的接口,可以把windjs的接口做的更加抽象,和正交... 既然windjs可以把异步转为同步,golang也有办法把同步转为异步,异步转成同步. 为什么不尝试提供golang的并行编程接口呢?
实现
golang 有2个接口和并行编程有关: 1.创建goroute(线程) 如:
go func(ch chan<- bool) { for { sleep(10); ch <- true; }} (c)
这个windjs本身已经提供.简单封装就可以了. 2.channel数据类型 如:go func(ch chan<- bool) { for { sleep(10); ch <- true; }} (c)
先用异步回调接口实现channel对象,后用windjs的接口把异步转为同步.实现了同步接口下的channel对象.可以改进的地方
1.创建goroute的方法可以省掉
.start()
2.没有实现带buffer的channel... 3.函数嵌套问题(不明白函数调用规则...召唤文档)