How to return many Promises and wait for them all before doing other stuff

后端 未结 5 1927
北荒
北荒 2020-11-21 23:02

I have a loop which calls a method that does stuff asynchronously. This loop can call the method many times. After this loop, I have another loop that needs to be executed o

5条回答
  •  半阙折子戏
    2020-11-21 23:36

    /*** Worst way ***/
    for(i=0;i<10000;i++){
      let data = await axios.get(
        "https://yourwebsite.com/get_my_data/"
      )
      //do the statements and operations
      //that are dependant on data
    }
    
    //Your final statements and operations
    //That will be performed when the loop ends
    
    //=> this approach will perform very slow as all the api call
    // will happen in series
    
    
    /*** One of the Best way ***/
    
    const yourAsyncFunction = async (anyParams) => {
      let data = await axios.get(
        "https://yourwebsite.com/get_my_data/"
      )
      //all you statements and operations here
      //that are dependant on data
    }
    var promises = []
    for(i=0;i<10000;i++){
      promises.push(yourAsyncFunction(i))
    }
    await Promise.all(promises)
    //Your final statement / operations
    //that will run once the loop ends
    
    //=> this approach will perform very fast as all the api call
    // will happen in parallal

提交回复
热议问题