Promise.all() 方法的使用

 Promise.all() 方法是一个 Promise 对象方法,可以将多个 Promise 实例包装成一个新的 Promise 对象,最终返回一个数组,其中包含所有 Promise 实例的返回值。

它的语法如下:

Promise.all(iterable);

  其中,iterable 参数是一个可迭代对象,它可以是一个数组、一个 Set 对象等,但是其中必须包含多个 Promise 实例。如果其中有任何一个 Promise 实例出现了错误或者被拒绝,最终的 Promise 对象也会失败并抛出错误。

Promise.all() 方法的使用场景包括多个异步操作的情况,可以将多个 Promise 实例合并起来,并在它们都完成之后进行统一处理,可以提高代码的效率和可读性。

下面是一个例子,演示如何使用 Promise.all() 方法合并多个异步操作:

const promise1 = new Promise((resolve, reject) => {
  setTimeout(() => resolve('promise1 resolved'), 1000)
})

const promise2 = new Promise((resolve, reject) => {
  setTimeout(() => resolve('promise2 resolved'), 2000)
})

const promise3 = new Promise((resolve, reject) => {
  setTimeout(() => resolve('promise3 resolved'), 3000)
})

Promise.all([promise1, promise2, promise3]).then(values => {
  console.log(values)  // ['promise1 resolved', 'promise2 resolved', 'promise3 resolved']
})

 在这个例子中,使用 Promise.all() 方法将三个 Promise 实例合并起来,最终返回一个新的 Promise 对象。在新的 Promise 对象的回调函数中,可以获取每个 Promise 实例的返回值,并将其打印在控制台上。

另外,需要注意的是, Promise.all() 方法会等待所有 Promise 实例完成,即所有 Promise 实例的状态都变为 resolved 或者其中任何一个 Promise 实例的状态变为 rejected 才会结束。因此,在使用 Promise.all() 方法时需要确保传入的所有 Promise 实例都能够有结果返回。否则,会导致该方法一直处于等待状态,无法结束。

实际项目中应用案例: 由于这部分代码在项目中多次使用,这里封装成一个方法以便复用。需要注意的是,涉及到异步操作,需要在方法内部返回一个 Promise 对象或者使用 async/await 等方式,以确保异步操作完成后返回数据。

// 获取站点信息
getSationInfo(this.stationCode).then(response => {
this.stationInfo = response.data;
});

//获取因子
this.ParamConfList();

let query = {
  stationCode: this.stationCode,
  searchType: this.dataType
};

// 获取表格标题行
getTableHeader(query).then(response => {
  this.tableHeader = response.data;
})

 下面将这段代码封装成一个名为 getStationData方法

methods: {
  async getStationData() {
    const query = {
      stationCode: this.stationCode,
      searchType: this.dataType
    };

    try {
      const [infoResponse, headerResponse] = await Promise.all([
        getSationInfo(this.stationCode),
        getTableHeader(query)
      ]);

      this.stationInfo = infoResponse.data;
      this.tableHeader = headerResponse.data;
      this.ParamConfList();
    } catch (error) {
      console.log(error);
    }
  }
}

 在这个例子中,使用了 Promise.all() 方法将两个异步操作合并成一个 Promise 对象,并使用 async/await 等方式等待异步操作完成。

使用这个方法时,可以将原来的代码替换为调用 getStationData() 方法的代码:

this.getStationData();

 这样就可以在代码中多次复用 getStationData() 方法,而不必每次都编写相同的代码。

猜你喜欢

转载自blog.csdn.net/m0_62323730/article/details/131130935