如何嵌套多个Promise.all

Rah*_*dav 2 javascript reactjs es6-promise

我有多个承诺数组

每个数组都放在一个 Promise.all()

then()每个的Promise.all()一个添加的数据tempObject

我需要在完成所有操作tempObject后设置为状态.then()Promise.all()

实现这一目标的最佳方法(干净且可读的代码)是什么?

下面是我的代码

callSomeApis(parameter){
  let tempArray1 = [];
  let tempArray2 = [];
  this.props.dispatch(actions.callApi1(parameter)).then(callApi1Result =>{
    let callApi1ResultArray = callApi1Result.data.data;
    let PromiseArr1 = callApi1ResultArray.map((callApi1ResultArrayItem) => {
      return this.props.dispatch(actions.callApi2(callApi1ResultArrayItem.itemId));
    });
    let PromiseArr2 = callApi1ResultArray.map((callApi1ResultArrayItem) => {
      return this.props.dispatch(actions.callApi3(callApi1ResultArrayItem.itemId,parameter));
    });
    let PromiseArr3 = callApi1ResultArray.map((callApi1ResultArrayItem) => {
      return this.props.dispatch(actions.callApi4(callApi1ResultArrayItem.itemId));
    });
    Promise.all(PromiseArr1).then((callApi2Result) => {
      callApi2Result.map((callApi2ResultItem,index) => {
        callApi1ResultArray[index].api2Details = callApi2ResultItem.data.data[0];
        tempArray2.push({id: callApi2ResultItem.data.data[0].id, text: callApi2ResultItem.data.data[0].text});
      });
      this.setState(prevState => {
        return{
          stateKey1: {
            ...prevState.stateKey1,
            innerStateKey1: {
              ...prevState.stateKey1.innerStateKey1,
              list: tempArray2
            }
          }
        }
      });
    });
    Promise.all(PromiseArr2).then((callApi3Result) => {
      callApi3Result.map((callApi3ResultItem, index) => {
        callApi1ResultArray[index].api3Result = callApi3ResultItem.data.data;
      });
    });
    Promise.all(PromiseArr3).then(callApi4Result => {
      callApi4Result.map((callApi4ResultItem,index) => {
        callApi1ResultArray[index].api4Result =  callApi4ResultItem.data.data;
      });
    });
    /**need to call this after the thens of  PromiseArr1, PromiseArr2 and PromiseArr3 are done executing*/
    this.setState({
      stateKey2:callApi1ResultArray
    })
    /** */
  })
}
Run Code Online (Sandbox Code Playgroud)

riw*_*iwu 5

Promise.all 返回一个承诺,你可以这样做:

const p1 = Promise.all(PromiseArr1).then(...);
const p2 = Promise.all(PromiseArr2).then(...);
const p3 = ...
Promise.all([p1, p2, ...]).then(...);
Run Code Online (Sandbox Code Playgroud)

如果你的所有承诺非常相似,你可以通过创建一个数组并将其映射到promises来清理它.


Tyl*_*ian 3

如果可以的话,您还可以使用async/await

async function (...) {
  const r1 = await Promise.all(...);
  // do something with r1
  const r2 = await Promise.all(...);
  // ...
}
Run Code Online (Sandbox Code Playgroud)

等等。不过,请确保您使用的是Promise.all可以并行化的操作(也返回 a Promise)。

我发现async/await确实清理了一些令人讨厌的Promise链/嵌套,并且对可读性有很大帮助。