I'm writing a Javascript function that pulls words out of a CloudDB database and puts them in one of three arrays: verb, adjective, or noun. Once all the words are in place and the last loop runs, I want to run the next function. Here's the code:
function verbnoun(array){
verbs = [];
adjectives = [];
nouns = [];
for (i = 0; i<array.length; i++){
//console.log(i); <-- returns 0,1,2,3...57,58 as expected
my_db.get(array[i], function(err, doc) {
if (!err){
if (doc.type == "verb"){
verbs.push(doc.word);
}
else if (doc.type == "adjective"){
adjectives.push(doc.word);
}
else if (doc.type == "noun"){
nouns.push(doc.word);
}
}
//console.log(i); <-- returns 59,59,59,59,59
if (i+1 == array.length){
nextFunction(verbs, adjectives, nouns);
}
});
}
}
But I can't figure out how to run the next function after the last loop. If I try to run it outside of the for loop, I just get empty arrays. Using an if statement to trigger on the last loop doesn't seem to work either, because the "i" in the for loop is stuck on 59 each time instead of counting up from 0,1,2,3,etc (see comment in code), so I can't single out which is the last loop.
This is my first post on StackExchange, so thanks for your patience.