H5和ArkTS交互,H5页面首次获取不到原生侧接口返回数据

问题1 :Logger.error 打印getCache返回2打印有数据,但是html 端接受不到

getCache(parameter: Object): Promise<string> { 
  Logger.error('getCache调用', parameter.toString()); 
  this.KeyValueBean = JSON.parse(parameter.toString()) 
  return new Promise((resolve) => { 
  StorageUtils.get(this.KeyValueBean.key,this.KeyValueBean.content).then((result) => { 
  Logger.error('getCache返回2',  result.toString()); 
  resolve(result.toString()); 
}) 
}) 
}

问题2 : 断点打印先实行的 return this.mFruit;返回为空 然后才打印log这种第一次点击接收不到值,第二次才能接受的

getCache(parameter: Object): string { 
  Logger.error('getCache调用', parameter.toString()); 
  this.KeyValueBean = JSON.parse(parameter.toString()) 
  StorageUtils.get(this.KeyValueBean.key,this.KeyValueBean.content).then((result) => { 
    this.mFruit = result.toString(); 
    Logger.error('getCache返回2',  this.mFruit); 
  }) 
  return this.mFruit; 
}
HarmonyOS
2024-08-02 18:05:19
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
在攒六便士

ArkTS访问首选项提供了异步和同步两种方式,上面遇到的问题可能是访问的异步方法导致,有两种解决方案

方案1: 将 ets 和 html中的方法都改成异步调用

// xxx.ets 中异步方法 
async  getCache(parameter: Object): Promise<string> { 
  console.log("打印="+parameter.toString()) 
  this.KeyValueBean = JSON.parse(parameter.toString()) 
  let result = await StorageUtils.get(this.KeyValueBean.key,this.KeyValueBean.content); 
  return  result.toString(); 
}
// xxx.html 调用处也改成异步调用 
window.jsBridge_jzt.getCache(JSON.stringify(json)).then((res)=>{ 
  $("#result").text(res); 
})

方案2: 将 ets 和 html中的方法都改成同步调用,同时将所以调用首选项的异步方法都改成同步的(带Sync的方法)

// xxx.ets写法 
getCache(parameter: Object): string { 
  console.log("打印="+parameter.toString()) 
  this.KeyValueBean = JSON.parse(parameter.toString()) 
  // 方法里调用数据库方法改成同步方法   
  let result = StorageUtils.getSync(this.KeyValueBean.key,this.KeyValueBean.content) ; 
  this.mFruit = result; 
  console.log("打印返回数据"+parameter.toString()) 
  return this.mFruit; 
}
// xxx.html 写法 
$("#result").text(window.jsBridge_jzt.getCache(JSON.stringify(json)));
分享
微博
QQ
微信
回复
2024-08-02 22:06:11
相关问题
HarmonyOS 原生H5页面交互
1004浏览 • 1回复 待解决
HarmonyOS H5原生交互
1286浏览 • 1回复 待解决
HarmonyOS H5应用数据交互
1650浏览 • 1回复 待解决
H5页面如何与ArkTS交互
4707浏览 • 1回复 待解决
Web组件h5页面如何交互
1339浏览 • 1回复 待解决
HarmonyOS h5原生交互页面状态机
1065浏览 • 1回复 待解决
HarmonyOS web原生H5如何交互
1771浏览 • 1回复 待解决
HarmonyOS H5与应用数据交互的Demo
1772浏览 • 1回复 待解决
HarmonyOS ArkTSH5交互方法
1226浏览 • 1回复 待解决
HarmonyOS webview 怎么H5交互
1095浏览 • 1回复 待解决
Web中webviewH5交互
2303浏览 • 1回复 待解决
HarmonyOS ArkTSh5数据解析
1040浏览 • 1回复 待解决
HarmonyOS h5页面缩放问题
2496浏览 • 2回复 待解决
HarmonyOS h5ArkTS通信
1389浏览 • 1回复 待解决
HarmonyOS web与H5交互
1937浏览 • 1回复 待解决
HarmonyOS H5页面localstorage为null
1271浏览 • 1回复 待解决
HarmonyOS webview H5页面事件监听
1901浏览 • 1回复 待解决