以下是AI给的建议,未实际验证.
// config flags(按你的项目常量来,用 CC_DEBUG / CC_DEV 也行)
const __DEV__ = typeof CC_DEBUG !== 'undefined' ? CC_DEBUG : true;
type Options = {
log?: boolean; // 是否打印 warn/error
rethrow?: boolean; // 发生异常后是否继续抛出给上层
afterCheck?: boolean;// 是否在 await 后再二次校验(默认 true)
};
export function promise_function(options: Options = {}) {
const { log = __DEV__, rethrow = true, afterCheck = true } = options;
return function (_: any, __: string, descriptor: PropertyDescriptor) {
const original = descriptor.value;
descriptor.value = async function (...args: any[]) {
// 1) 执行前校验
const node: cc.Node | undefined = (this as any)?.node;
if (!node || !cc.isValid(node, true)) { // 第二个参数true: 包括正在销毁的情况
if (log) cc.warn('[promise_function] node invalid before:', original.name);
return;
}
try {
const ret = await original.apply(this, args);
// 2)(可选)执行后再校验一次,防“中途被销毁”
if (afterCheck) {
if (!cc.isValid(node, true)) {
if (log) cc.warn('[promise_function] node invalid after:', original.name);
return;
}
}
return ret;
} catch (err) {
if (log) cc.error('[promise_function] error in', original.name, err);
if (rethrow) throw err; // 默认:记录后继续抛,让上层能感知
return;
}
};
return descriptor;
};
}
使用:
@promise_function({ log: true, rethrow: true }) // 开发期
async function1 () {
const res = await this.fakeAsyncLoad();
this.node.setPosition(cc.v3(0, 0, 0));
}
// 需要极致性能的构建(发布态)可以这样统一关闭日志:
@promise_function({ log: false, rethrow: true })

