HarmonyOS鸿蒙Next中使用第三方库protobuf_format时,语句:await Protobuf.loadProtoFile() 报错:Top-level 'await' expressions are only allowed when the ...

HarmonyOS鸿蒙Next中使用第三方库protobuf_format时,语句:await Protobuf.loadProtoFile() 报错:Top-level ‘await’ expressions are only allowed when the … 使用第三方库protobuf_format时,语句:await Protobuf.loadProtoFile() 报错:

Top-level ‘await’ expressions are only allowed when the ‘module’ option is set to ‘es2022’, ‘esnext’, ‘system’, ‘node16’, or ‘nodenext’, and the ‘target’ option is set to ‘es2017’ or higher.

cke_1016.png


更多关于HarmonyOS鸿蒙Next中使用第三方库protobuf_format时,语句:await Protobuf.loadProtoFile() 报错:Top-level 'await' expressions are only allowed when the ...的实战教程也可以访问 https://www.itying.com/category-93-b0.html

3 回复
async onPageShow(): Promise<void> {
	let builder:ESObject = await Protobuf.loadProtoFile("userproto.proto", null, null, getContext(this).resourceManager);
}

更多关于HarmonyOS鸿蒙Next中使用第三方库protobuf_format时,语句:await Protobuf.loadProtoFile() 报错:Top-level 'await' expressions are only allowed when the ...的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中使用第三方库protobuf_format时,语句await Protobuf.loadProtoFile()报错“Top-level ‘await’ expressions are only allowed when the…”的原因是await关键字只能在async函数内部使用。await用于等待一个异步操作完成,而async函数是允许使用await的异步函数。

在JavaScript或TypeScript中,await必须在async函数内部使用。如果在顶层直接使用await,会导致语法错误。解决方法是将await Protobuf.loadProtoFile()放在一个async函数中,例如:

async function loadProto() {
    await Protobuf.loadProtoFile();
}

loadProto();

或者使用立即执行函数表达式(IIFE):

(async function() {
    await Protobuf.loadProtoFile();
})();

这样可以确保awaitasync函数内部使用,避免语法错误。

在HarmonyOS鸿蒙Next中使用protobuf_format时,await Protobuf.loadProtoFile()报错是因为await关键字只能在async函数内部使用。你需要将这段代码包裹在一个async函数中,或者在顶层使用async立即执行函数。例如:

async function loadProto() {
    await Protobuf.loadProtoFile();
}

loadProto();

或者使用立即执行函数:

(async () => {
    await Protobuf.loadProtoFile();
})();

这样可以确保await在异步上下文中正确执行。

回到顶部