需求描述

  • 我的页面有5个请求接口的方法,然后我需要在另外一个方法中调用这几个方法,并让他们按照我想要的顺序执行。

代码实现

  • 接下来直接看代码关于我是如何实现这个需求的
// 这个方法是一个请求接口的方法,其他每个也这样写
getStatisticsList() {
	/* 1.return一个promise对象,promise的构造函数传入一个对象,这个对象是一个函数,
	这个函数可以传两个对象,分别标志成功和失败,我这里只传了一个成功标志即resolve,
	resolve中必须有一个返回值,(可以是标志,也可以是data数据)来使得下一步可以进行,
	我这里给resolve返回了一个true,因为我不需要这个函数返回的其它信息来执行下一步,我只需要它标志一下它运行完成了即可 */
      return new Promise(resolve => {
        var url = 'BigScreenComponent/CarTodayInfos'
        var param = null
        AjaxGet(
          url,
          param,
          response => {
            this.optionModel.statisticToday = response
            this.$nextTick(() => {
            // console.log(this.gauge4)
            })
            resolve(true)  // resolve返回true
          }
        )
      })
    },
  • 下一步就是使用promise的then方法来使我的方法可以逐个运行
timer() {
/* 这里的每个方法都加过了promise构造函数,然后按顺序给每个方法加.then,
   then里的response的值就是promise返回的参数resolve的值
   这样我们的多个方法就是按我们写好的顺序执行的 */
      this.getStatisticsList().then(response => {
        if (response) {
          return this.getGagueList()
        }
      }).then(response => {
        if (response) {
          return this.getLastCar()
        }
      }).then(response => {
        if (response) {
          return this.getPieList()
        }
      }).then(response => {
        if (response) {
          return this.getWarningData()
        }
      }).then(response => {
        if (response) {
          return this.sametimeUpdate()
        }
      }).then(response => {
        if (response) {
          this.timerparam = setTimeout(this.timer, 10000)
        }
      })
    },

小小总结

网上promise的讲解一大堆,我这里只是promise最基础的使用,介绍的比较简略。
本人是第一次使用这个功能,了解的也不够深入,但确实感觉到了这个功能的强大,所以记录一下,防止忘记

Logo

前往低代码交流专区

更多推荐