zoukankan      html  css  js  c++  java
  • vue-promise的all方法使用

      在一个函数里面,需要发送多个ajax请求,并且下一个请求都需要上一个请求返回的数据,那我们可以下面的做法:

      new Promise((resolve, reject) => {
        //执行异步请求
        $.get("test.cgi", {
            name: "John",
            time: "2pm"
          },
          function (data) {
            resolve(data)
          });
      }).then(data => {
        console.log('请求成功1')
    
        return new Promise(resolve => {
          $.get("test.cgi", {
            name: "John",
            time: "2pm"
          },
          function (data) {
            resolve(data)
          });
        }).then(resolve => {
          console.log('请求成功2')
        })
      })

      但有时候也不是需要下一个请求要上一个请求的数据,两个请求各自不相干,但我们要求两个请求执行完毕后,再拿他们的数据进行统一处理,promise提供了一个all方法能让我们做到:

      Promise.all([
        new Promise(resolve => {
          $.get("test.cgi", {
            name: "John",
            time: "2pm"
          },
          function (data) {
            resolve(data)
          })
        }),
        new Promise(resolve => {
          $.get("test.cgi", {
            name: "John",
            time: "2pm"
          },
          function (data) {
            resolve(data)
          })
        })
      ]).then(response => {
        console.log(response[0])
        console.log(response[1])
      })

      all要传入一个数组,数组的元素是一个 Promise对象,相当封装一个异步操作;当数组中的所有Promise的异步操作执行完毕,那就会调用then进行处理,参数response包含了所有的promise返回的数据,是一个数组,response[0]表示第一个promise返回的数据,以此类推。

  • 相关阅读:
    Win10 UWP Tile Generator
    Win10 BackgroundTask
    UWP Tiles
    UWP Ad
    Win10 build package error collections
    Win10 八步打通 Nuget 发布打包
    Win10 UI入门 pivot multiable DataTemplate
    Win10 UI入门 导航滑动条 求UWP工作
    UWP Control Toolkit Collections 求UWP工作
    Win10 UI入门 SliderRectangle
  • 原文地址:https://www.cnblogs.com/ibcdwx/p/14614197.html
Copyright © 2011-2022 走看看