Without using a Promise or temp state, I don't know of another way to return an aggregated result off the top of my head. The simple/synchronous example here would only be useful for looping through queries where you don't need an aggregated return, I.E. some forms of bulk writes or some other outgoing requests which aren't displayed to the user directly.
To see the results logged sequentially, we'd need to do modify it to something like this:
var rows = [{ a: 1 }, { a: 2 }, { a: 3 }, { a: 4 }];
function runQuery (i) {
if (i >= rows.length) {
console.log('Finished running all queries');
return "Hello World";
}
var data = rows[i];
console.log('BEFORE RUN #'+i);
query1.trigger({
additionalScope: {
data: data
},
// You can use the argument to get the data with the onSuccess function
onSuccess: function(data) {
let myResult = data
console.log(myResult)
console.log("AFTER RUN #"+i)
runQuery(i + 1);
}
});
}
runQuery(0);
Which gives us this console output:
If you need to return aggregated data for a loop of .trigger()
's of unknown length (I.E. the query is only known to be complete based the return of one of the individual queries) then you'll probably need to use a temporary state with a default value of []
and .setIn(index, data)
to save results as they are returned inside the onSuccess function of the loop. There's an example of doing this with the airtable api here: Keep running REST API requests until all results are returned (Load all rows from an Airtable API)