【快应用】如何获取异步回调方法中返回的值

背景:异步回调或者异步promise的方式调用给参数deviceInfo赋值,然后再通过console日志输出,打印的参数的值为空,该如何处理?

相关代码:

<script>

  import push from "@service.push";

  import device from '@system.device';

  const injectRef = Object.getPrototypeOf(global) || global;

  // injection regeneratorRuntime

  injectRef.regeneratorRuntime = require('@babel/runtime/regenerator');

  module.exports = {

    data: {

      deviceInfo: ''

    },

    onCreate() {

      this.testAsync();

      console.log("this.$def.data:", this.$def.data);

    },

    async testAsync() {

      try {

        let res = await device.getInfo();

        console.info("get device id " + JSON.stringify(res.data));

        this.$def.data.deviceInfo = res.data

      } catch (e) {

        console.log("get device id error " + e.code);

      }

    },

    onDestroy() {

      console.info("Application onDestroy");

    },

    dataApp: {

      localeData: {}

    }

  };

</script>

运行效果:

cke_834.png

原因及解决方案:

异步方法的回调方法是异步返回的,调用该方法后,立刻打印该方法中的值,此时异步方法还未执行完成,就会导致后面打印的值为空。可以加50ms的延时待异步方法返回结果后再去执行后面的代码。

示例代码:

<script>

  import push from "@service.push";

  import device from '@system.device';

  const injectRef = Object.getPrototypeOf(global) || global;

  // injection regeneratorRuntime

  injectRef.regeneratorRuntime = require('@babel/runtime/regenerator');

  module.exports = {

    data: {

      deviceInfo: ''

    },

    onCreate() {

      this.testAsync();

      setTimeout(() => {

        console.log("this.$def.data:", this.$def.data);

      }, 50);

 

    },

    async testAsync() {

      try {

        let res = await device.getInfo();

        console.info("get device id " + JSON.stringify(res.data));

        this.$def.data.deviceInfo = res.data

      } catch (e) {

        console.log("get device id error " + e.code);

      }

    },

    onDestroy() {

      console.info("Application onDestroy");

    },

    dataApp: {

      localeData: {}

    }

  };

</script>

运行效果:

cke_2830.png

欲了解更多更全技术文章,欢迎访问https://developer.huawei.com/consumer/cn/forum/?ha_source=zzh

posted @ 2022-08-11 20:12  华为开发者论坛  阅读(68)  评论(0编辑  收藏  举报