教你实现快应用storage接口同步调用

2,140 阅读1分钟

快应用异步接口支持返回Promise(1010+)的方式,开发者配套async和await的方式编写代码,达到同步效果。对于接口调用成功是返回一个对象res = {data} ,开发者可以通过res.data获取接口实际返回的结果,通过res.code获取失败的返回code。

以storage.get()接口为例,代码如下:

<script>
  import storage from '@system.storage';
  const injectRef = Object.getPrototypeOf(global) || global;
  // 注入regeneratorRuntime
  injectRef.regeneratorRuntime = require('@babel/runtime/regenerator');
 
  module.exports = {
    onDestroy: function () {
      console.info("onDestroy");
    },
    getValue:  async function () {
      try {
        let re = await storage.get({
        key: 'name'
      });
      console.info("getValue re="+JSON.stringify(re));
      let value=re.data;
      } catch (error) {
          console.info("getValue error="+error);
      }
    }
  }
</script>

输出如下:

getValue re={"data":"hanmeimei"}

注意事项:

对于await的方式调用需要引入@babel/runtime/regenerator。

欲了解更多详情,请参见:

快应用回调介绍:

developer.huawei.com/consumer/cn…

原文链接:developer.huawei.com/consumer/cn…

原作者:Mayism