Vue Promise的使用,界面使用异步线程循环执行方法(模拟线程)

目录

1.定义开始和退出标识

2.定义开始方法--异步

3.定义循环方法,以及控制规则

4.定义业务方法


1.定义开始和退出标识

为的是能控制开始和结束,记得销毁时要结束循环,否则方法会一直被执行

data() {
      return {
        isrunning: false, // 轮询的标识
      }
    },

2.定义开始方法--异步

async 标识方法为异步,使用 store 异步调用一个方法,回调方法也标识为 async

然后再回调方法里边执行循环方法

      // 开始刷新
      async startRunning() {
        this.$store.dispatch('orderform/GetInExecutionOrder').then(async (res) => {
          this.runing()
        })
      },

3.定义循环方法,以及控制规则

先将标识isrunning 置为true

然后定义while (true)循环

当isrunning==false时退出循环

循环中控制下睡眠时间

其中index是调用业务方法的间隔周期

用50ms来控制,是希望能及时响应标识isrunning值的变化

        index = index - 50
          if (index <= 0) {
            index = 5000
          }

调用的业务方法 : await this.getOrderState();

async runing() {
        this.isrunning = true;
        await global.sleep(1000)
        var index = 5000
        while (true) {
          if (!this.isrunning) {
            break;
          }
          if (index >= 5000) {
            try {
              await this.getOrderState();
            } catch (error) {
              break; // 如果发生错误,退出循环
            }
          }
          await global.sleep(50)
          index = index - 50
          if (index <= 0) {
            index = 5000
          }
        }
      },

4.定义业务方法

用Promise实现异步调用

记得一定要执行回调方法  resolve();

如果里边还使用了store,就必须要在store的回调方法中执行 resolve(); 

否则会卡死在这个方法里

async getOrderState() {
        //实时刷新订单状态
        return new Promise((resolve) => {
          this.$store.dispatch('orderform/GetInExecutionOrder').then((res) => {
              resolve();
            })
          })
        });
      },

结束循环 不同的钩子节点下都可以,看实际需求

beforeUnmount() {
      this.stopPolling()
    },
    beforeRouteLeave(to, from, next) {
      // 在这里执行清理操作
      this.stopPolling()
      this.isrunning = false;
      next()
    },
    unmounted() {
      this.stopPolling()
      this.isrunning = false;
    },

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Rotion_深

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值