目录

异步接口如何以同步的方式进行调用

问题现象

在API文档中,setSpecificSystemBarEnabled接口只有Promise异步回调的方法,如何以同步的方式进行调用?

背景知识

解决方案

目前HarmonyOS未提供setSpecificSystemBarEnabled的同步设置方法,可以使用async/await让异步代码的写法更接近同步逻辑。

import { window } from '@kit.ArkUI';
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct SpecificSystemBarEnabledSample {
  context = this.getUIContext().getHostContext() as common.UIAbilityContext;
  @State flag: boolean = true;

  /**
   * setSpecificSystemBarEnabled的同步设置方法
   */
  set() {
    window.getLastWindow(this.context, async (err: BusinessError, topWindow) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
        return;
      }
      try {
        await topWindow.setSpecificSystemBarEnabled('status', this.flag);
      } catch (exception) {
        console.error(`Failed to set the system bar to be invisible. Cause code: ${exception.code}, message: ${exception.message}`);
      }
    });
  }

  build() {
    RelativeContainer() {
      Text('点击测试')
        .id('SpecificSystemBarEnabledSample')
        .fontSize($r('app.float.page_text_font_size'))
        .fontWeight(FontWeight.Bold)
        .alignRules({
          center: { anchor: '__container__', align: VerticalAlign.Center },
          middle: { anchor: '__container__', align: HorizontalAlign.Center }
        })
        .onClick(() => {
          this.set();
          this.flag = !this.flag;
        })
    }
    .height('100%')
    .width('100%')
  }
}