找回密码
 立即注册
搜索

storage接口有同步的执行方法吗?

1
回复
434
查看
[复制链接]

46

主题

47

帖子

465

积分

 楼主| 2021-8-20 16:01:58 显示全部楼层 |阅读模式

storage接口有同步的执行方法吗?


回复

使用道具 举报

23

主题

142

帖子

825

积分

2021-8-20 16:04:14 显示全部楼层

快应用异步接口支持返回Promise的方式,开发者配套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。

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册