Promise处理多个AJAX异步请求

在一个页面中,有时会遇到多个ajax请求 同时发生,这样不能保证它们的运行顺序,会导致数据出错,

如果有loading动画时,你不能保证哪个请求先完成,来结束动画。

如果两个数据有关联,必须先完成哪个再执行下一个,可以这样来操作。

可以看到上面的代码是一个相对简单的promise结构。

我们先new promise,在参数列表有两个参数,一个resolve一个rejects。通俗的来讲,

resolve相当于ajax中的success,rejects则就是catch。当然,这两个单词可以随便取,也可以在参数列表写上a,b。但是他们代表的意思是一模一样的。在后面我们可以看到一行代码“resolve()”,这就相当于return。

在promise里面的代码块会最先执行,然后resolve(),接着会运行then里面的方法。

在then里面也有参数,()=> {/代码块/},因为我在上面代码中resolve()的括号中并没有写参数,所以可以看成它返回的是一个空的结果集,所以我在then后面有()来接受,因为是空结果集,所以我用()来接收。

当然你也可以返回想要的结果,打个比方,我把代码改成下面这样

我让resolve返回了一个值,然后在then里面打印出来。

可以看到,res被打印出来就是返回的值1。

Promise.all()  :

created(){
    this.init()
},
methods: {
    init () {
      this.$store.dispatch('setLoading', true)
      const Ajax = new Promise((resolve, reject) => {
        getAllRecruiter().then(res => {
          this.recruiter.option = res.data
          this.recruiter.val = res.data[0]
          resolve(res)  // 请求成功后,利用resolve改变promise状态,并且作为返回值传回到promise对象
        }).catch((err) => {
          reject(err); // 请求失败则利用reject改变状态,终止当前函数流
        })
      })
      const Ajax0 = new Promise((resolve, reject) => {
        getAllEmploymentType().then(res => {
          this.employmentType.option = res.data
          resolve()
        }).catch(() => {

        })
      })
      const Ajax1 = new Promise((resolve, reject) => {
        getAllLevel().then(res => {
          this.careerLevel.option = res.data
          resolve()
        }).catch(() => {

        })
      })
      const Ajax2 = new Promise((resolve, reject) => {
        getAllBenefit().then(res => {
          this.benefits.option = res.data
          resolve()
        }).catch(() => {

        })
      })
      Promise.all([Ajax, Ajax0, Ajax1, Ajax2]).then(() => 
{
       //所有请求都成功后执行函数
        this.getOldData()
      }).catch(() => {
      //// 异常处理
        this.$store.dispatch('setLoading', false)
      })
    }
}    

-----------------------------

部分文章来自:https://blog.csdn.net/qq_39861508/article/details/78925118

猜你喜欢

转载自www.cnblogs.com/listen9436/p/10876158.html