Finish all asynchronous requests before loading data?

前端 未结 6 921
被撕碎了的回忆
被撕碎了的回忆 2020-11-27 18:57

I have run into an issue where I have multiple asynchronous requests occuring which grab images and information from the Facebook API and my Firebase database. I want to per

6条回答
  •  一个人的身影
    2020-11-27 19:54

    One Idea i have used is to place an if statement check inside the query statement call back and place the query statement call back in a for loop (so you can loop through all of your queries), so the if statement should check if this the last call back expected, then you should execute a return statement or a deferred.resolve statement, the following is a concept code.

    var list=fooKeys //list of keys (requests) i want to fetch form firebase
    var array=[]  // This is the array that will hold the result of all requests 
    for(i=xyz;loop breaking condition; i++){
        Ref = new Firebase("https://yourlink.firebaseio.com/foo/" + fooKeys[i]);
       Ref.once("value", function (data) {
           array.push(data.val());
           if(loop breaking condition == true){
               //This mean that we looped over all items
               return array;  //or deferred.resolve(array);
           }
       })
    }
    

    Putting this code in a function and call it asynchronously will give you the ability to wait for the whole results before proceed in doing other stuff.

    Hope you (and the others) find this beneficial.

提交回复
热议问题