我正在编写一个 Javascript 函数,从 CloudDB 数据库中提取单词并将它们放入三个数组之一:动词、形容词或名词。一旦所有单词都就位并且最后一个循环运行,我想运行下一个函数。这是代码:
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);
}
});
}
但是我不知道如何在最后一个循环之后运行下一个函数。如果我尝试在 for 循环之外运行它,我只会得到空数组。使用 if 语句触发最后一个循环似乎也不起作用,因为 for 循环中的“i”每次都卡在 59 而不是从 0、1、2、3 等开始计数(见评论在代码中),所以我无法挑出最后一个循环。
这是我在 StackExchange 上发表的第一篇文章,感谢您的耐心等待。
最佳答案
您正遭受 i
的关闭,在任何 get
调用返回并触发其回调之前,它(可能)一直增加到 59。
本质上,i
表示发送 的请求数,而不是成功返回的请求数。您需要一个不同的计数器来跟踪该值。
function verbnoun(array) {
verbs = [];
adjectives = [];
nouns = [];
// New counter for completed requests
var finished = 0;
for (i = 0; i < array.length; i++) {
//console.log(i); <-- returns 1,2,3...57,58,59 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 (++finished == array.length) {
nextFunction(verbs, adjectives, nouns);
}
});
}
}
关于Javascript:如何在上一个函数的最终for循环完成后运行一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30331621/