参考:
https://blog.csdn.net/a42626423/article/details/135101768
https://blog.csdn.net/a42626423/article/details/135101768
例如,加载资源代码用回调函数的写法:
传参数可以少写,还带容错
//加载resources下文件
loadRes(url, type, completeCallback?, failCallback?) {
if (!url) {
console.error("url为空!!");
failCallback && failCallback();
return;
}
let extname = cc.path.extname(url);
if (extname) {
url = url.slice(0, - extname.length);
}
cc.resources.load(url, type, (err, asset: any) => {
if (err) {
console.error("加载失败", url, "\n", err);
// Editor.log("加载失败", url, err);
failCallback && failCallback();
return;
}
completeCallback && completeCallback(asset);
});
}
//调用
test(node: cc.Node) {
this.loadRes("image", cc.SpriteFrame, (res) => {
node.getComponent(cc.Sprite).spriteFrame = res;
}, () => {
})
}
用promise写法
//加载resources下文件
loadResNew(url, type) {
return new Promise<void>((resolve, reject) => {
if (!url) {
console.error("url为空!!");
reject({});
return;
}
let extname = cc.path.extname(url);
if (extname) {
url = url.slice(0, - extname.length);
}
cc.resources.load(url, type, (err: Error, asset: any) => {
if (err) {
console.error("加载失败", url, "\n", err);
reject(err);
return;
}
resolve(asset);
});
})
}
//调用
test(node: cc.Node) {
this.loadResNew("image", cc.SpriteFrame).then((res: any) => {
node.getComponent(cc.Sprite).spriteFrame = res;
}).catch((error: Error) => {
//失败处理
})
}
其余内容参考:
fun() {
return new Promise((resolve, reject) => {
let succ = Math.random() > 0.5
setTimeout(() => {
if (succ) {
resolve(null)
}
else {
reject(null)
}
}, 2000)
});
}
test() {
this.fun().then((data) => {
//成功处理resolve
}, (data) => {
//失败处理reject
})
//或者
this.fun().then((data) => {
//成功处理
}).catch((error: Error) => {
//失败处理
})
}
//加载多个
fun2() {
let loadArr = []
return new Promise((resolve, reject) => {
Promise.all(loadArr).then(() => {
//loadArr都执行完之后
resolve(null);
}).catch((error: Error) => {
//loadArr出错
resolve(null);
})
});
}
//链式调用
test2() {
let p = new Promise(resolve => {
setTimeout(() => {
resolve("success 1")
}, 2000)
})
p.then((info) => {
// 此处继续返回一个promise对象,形成链式调用
return new Promise(resolve => {
console.log("info = ", info)
setTimeout(() => {
resolve("success 2")
}, 2000)
})
}).then((info) => {
console.log("info = ", info)
}).catch((error: Error) => {
//失败处理
})
}