since是什 关于SINCE的全部用法( 六 )


6、在实际开发中的用法
先看一个在Egret上常用的方法getResByUrl的使用:
RES.getResByUrl("resource/assets/egret_icon.png", (data)=> {
let icon: egret.Bitmap = new egret.Bitmap(data);
this.addChild(icon);
}, this, RES.ResourceItem.TYPE_IMAGE);
API中:
function getResByUrl(url: string, compFunc?: Function, thisObject?: any, type?: string): Promise;
可以看到getResByUrl 加载一个路径的图片资源,加载完成后执行comFunc回调函数,通过回调函数加载此图片资源,显示出来 。我们可以拆分一下这个步骤,如下:
private urlGetImg() {
let result: Promise = RES.getResByUrl("resource/assets/egret_icon.png");
result.then((data)=> {
let icon: egret.Bitmap = new egret.Bitmap(data);
icon.x = egret.MainContext.instance.stage.stageWidth - icon.width;
this.addChild(icon);
})
}
二者结果相同,都可以通过路径把图片加载出来 。
下面另外一个例子,参考Nasus
创建5 .5个对象,异步依次执行一系列操作,效果如下图 。
本次所有行为执行完毕之后,才可以进入下一次操作 。使用到tween第三方库,源码如下:
private orderTW() {
for (let i = 0; i < 5; i++) {
for (let j = 0; j < 5; j++) {
let map: egret.Bitmap = new egret.Bitmap(RES.getRes("egret_icon_png"));
map.anchorOffsetX = map.width / 2;
map.anchorOffsetY = map.height / 2;
map.x = map.width .j;
map.y = map.height .i;
this._layer.addChild(map);
this._layer.x = egret.MainContext.instance.stage.stageWidth / 2 - this._layer.width / 2;
this._layer.y = egret.MainContext.instance.stage.stageHeight / 2 - this._layer.height / 2;
}
}
//当前下标
let index: number = 0;
//执行动作的Promise
let twPromise = () => {
console.log(`执行${index}次`);
return new Promise((resolve1, reject) => {
egret.Tween.get(this._layer.getChildAt(index)).to({
rotation: 30
}, 400).to({
rotation: -30
}, 400).to({
alpha: 0
}, 200).call(() => {
resolve1(index++);
})
})
}
//切换对象的Promise
let orderPromise = () => {
return new Promise((resolve2, reject) => {
twPromise().then(() => {
if (index < this._layer.numChildren) resolve2(orderPromise())
else resolve2("执行完毕")
})
})
}
orderPromise();
}
定义两个Promise方法,分别为tween动画的twPromise和执行twPromise方法的orderPromise方法,orderPromise在初始的时候执行,执行此方法会调用twPromise方法和twPromise的then方法,其中then方法会调用index++,也就是一个对象执行一系列tween动画后,切换下一个对象,然后通过resolve2(orderPromise())使整个过程走完 。

猜你喜欢