HarmonyOS 首选项有时候存储会很慢,几秒钟或者更长

代码如下:

async setValue<T>(key: string, value: T): Promise<void> {
  if (this.preferences) {
  const str = JSON.stringify(value)
  Logger.info(TAG, `setValue preferences str=${str}`);
//有时候存储会很慢,几秒钟
this.preferences.put(key, str)
  .then(() => {
    Logger.info(TAG, `setValue preferences saveUserData`);
    this.saveUserData();
  })
  .catch((err: BusinessError) => {
    Logger.info(TAG, `setValue preferences catch = ${err.message}`);
  })
  .finally(() => {
    Logger.info(TAG, `selectHome preferences finally`);
  })
  } else {
    Logger.info(TAG, `setValue PREFERENCES_NAME`);
    this.initPreference(PREFERENCES_NAME).then(() => {
      Logger.info(TAG, `setValue setValue`);
      this.setValue<T>(key, value);
    });
  }
}
HarmonyOS
1天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
fox280

请参考示例如下:

import dataPreferences from '@ohos.data.preferences';
import { BusinessError } from '@ohos.base';


import { GlobalThis } from '../utils/GlobalThis';

let preferences: dataPreferences.Preferences | null = null;

let context = GlobalThis.getInstance().getContext("context")  // 获取context
try {
  let options: dataPreferences.Options = { name: 'myStore' };
  preferences = dataPreferences.getPreferencesSync(context, options);
  console.log("testtag success to get preferences");
} catch (err) {
  let code = (err as BusinessError).code;
  let message = (err as BusinessError).message;

  console.error(`testtag  Failed to get preferences. Code:${code},message:${message}`);
}


@Entry
@Component
struct Index {
  @State message: string = 'Hello World';

  build() {
    Row() {
      Column() {
        Button("写入数据")
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(()=>{
            try {
              if (preferences!=null && preferences.hasSync('startup')) {
                console.info("The key 'startup' is contained.");
              } else {
                console.info("The key 'startup' does not contain.");
                // 此处以此键值对不存在时写入数据为例
                if (preferences!=null) {
                  preferences.putSync('startup', 'auto');
                  preferences.putSync('startup1', 'auto1');
                  preferences.putSync('startup2', 'auto2');
                  preferences.putSync('startup3', 'auto3');
                }
              }
            } catch (err) {
              let code = (err as BusinessError).code;
              let message = (err as BusinessError).message;
              console.error(`testtag Failed to check the key 'startup'. Code:${code}, message:${message}`);
            }
          })
        Button("读取数据")
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(()=>{
            if (preferences != null) {
              try {
                let val = preferences.getSync('startup', 'default');
                console.info(`testtag Succeeded in getting value of 'startup'. val: ${val}.`);
              } catch (err) {
                let code = (err as BusinessError).code;
                let message = (err as BusinessError).message;
                console.error(`testtag Failed to get value of 'startup'. Code:${code}, message:${message}`);
              }
            }
          })
        Button("删除数据")
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(()=>{
            if (preferences != null) {
              try {
                preferences.deleteSync('startup1');
                console.log("删除数据成功");
              } catch (err) {
                let code = (err as BusinessError).code;
                let message = (err as BusinessError).message;
                console.error(`Failed to delete the key 'startup'. Code:${code}, message:${message}`);
              }
            }
          })
        Button("数据持久化")
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(()=>{
            if (context != null) {
              console.log("testtag"+context.preferencesDir);
            }
            if (preferences != null) {
              try {
                preferences.flush((err: BusinessError) => {
                  if (err) {
                    console.error(`Failed to flush. Code:${err.code}, message:${err.message}`);
                    return;
                  }
                  console.info('Succeeded in flushing.');
                })
              } catch (err) {
                let code = (err as BusinessError).code;
                let message = (err as BusinessError).message;
                console.error(`Failed to flush. Code:${code}, message:${message}`);
              }
            }
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}
分享
微博
QQ
微信
回复
1天前
相关问题
HarmonyOS 首选项超长string存储失败
33浏览 • 1回复 待解决
首选项存储问题,为什么会报错?
293浏览 • 1回复 待解决
HarmonyOS 创建首选项报错code:15500000
169浏览 • 1回复 待解决
HarmonyOS 首选项报错数据报错
31浏览 • 1回复 待解决
HarmonyOS TaskPool使用首选项报错
471浏览 • 1回复 待解决
HarmonyOS 首选项回调失效
17浏览 • 1回复 待解决
首选项获取实例,实例是否为单例
1972浏览 • 1回复 待解决
HarmonyOS 用户首选项是线程安全的吗
339浏览 • 1回复 待解决
HarmonyOS 模拟器使用首选项能力异常
116浏览 • 1回复 待解决
错误码15500000(首选项)如何处理?
1397浏览 • 1回复 待解决