I have a problem with the promise return code, I have a getTagQuotes function that contains a for loop that can make several API calls to return data to an array.
How my code for this starts below:
// If there are tags, then wait for promise here: if (tags.length > 0) { // Setting promise var to getTagQuotes: var promise = getTagQuotes(tags).then(function() { console.log('promise =',promise); // This array should contain 1-3 tags: console.log('tweetArrayObjsContainer =',tweetArrayObjsContainer); // Loop through to push array objects into chartObj: for (var i=0; i<tweetArrayObjsContainer.length; i++) { chartObj.chartData.push(tweetArrayObjsContainer[i]); } // Finally draw the chart: chartDirective = ScopeFactory.getScope('chart'); chartDirective.nvd3.drawChart(chartObj.chartData); }); }
GetTagQuotes return promise function:
function getTagQuotes(tags) { var deferred = $q.defer(); // setting the defer var url = 'app/api/social/twitter/volume/'; // My for loop, which only returns ONCE, even if there are 3 tags for (var i=0; i<tags.length; i++) { var loopStep = i; rawTagData = []; // The return statement return GetTweetVolFactory.returnTweetVol(url+tags[i].term_id) .success(function(data, status, headers, config) { rawTagData.push(data); // One the last loop, call formatTagData // which fills the tweetArrayObjsContainer Array if (loopStep === (rawTagData.length - 1)) { formatTagData(rawTagData); deferred.resolve(); return deferred.promise; } }); } function formatTagData(rawData) { for (var i=0; i<rawData.length; i++) { var data_array = []; var loopNum = i; for (var j=0; j<rawData[loopNum].frequency_counts.length; j++) { var data_obj = {}; data_obj.x = rawData[loopNum].frequency_counts[j].start_epoch; data_obj.y = rawData[loopNum].frequency_counts[j].tweets; data_array.push(data_obj); } var tweetArrayObj = { "key" : "Quantity"+(loopNum+1), "type" : "area", "yAxis" : 1, "values" : data_array }; tweetArrayObjsContainer.push(tweetArrayObj); } } }
Pay attention to this line.
return GetTweetVolFactory.returnTweetVol(url+tags[i].term_id)
inside the for loop:
for (var i=0; i<tags.length; i++)
Everything works fine if I only need to scroll once. However, as soon as another tag appears (up to 3), it returns only the first loop / data. It does not wait for the for loop to complete. Then return the promise. So my tweetArrayObjsContainer always has only the first tag.
source share