【发布时间】:2016-10-29 17:42:42
【问题描述】:
在我的代码中,我有 2 个 for 循环执行一个异步函数(这两个循环中的函数相同),但是在这 2 个循环之后,代码必须等到它们执行后才能运行。这是我的代码:
for(var a = 0; a < videoIds.length; a++){
if(videoIds){
findVideo(videoIds[a], function(thumbnailPath, videoName){ // findVideo is the async function
// it returns 2 values, thumbnailPath and videoName
videoNames[a] = videoName; // and then these 2 values are written in the arrays
thumbnaildPaths[a] = thumbnailPath;
console.log('1');
});
}
}
// then the above code runs one more time but with different values, so I won't include it here (it's the same thing)
enter code here
console.log('3');
// the rest of the code
// writes the values from the loops to the database so I can't run it many times
如果我运行代码,我会在看到 1 之前看到 3(来自 console.log 函数)。但正如我上面所说,我必须等待循环结束才能继续。 findVideo() 函数只包含 mongoose 提供的 Video.find({}) 方法,然后返回值 thumbnailPath 和 videoName。我需要做的是等待 2 个循环结束然后继续,但是由于显而易见的原因,我不能将其余代码放在循环中!有没有什么办法解决这一问题?谢谢!
【问题讨论】:
-
该函数的循环在那里,只是为了确保某些选定的视频确实存在并且它们是由用户上传的(确切地说是req.user)
-
你可以看看
asyncnpm 模块,用于管理异步控制流 -
使用承诺。他们是为此目的而存在的。 npmjs.com/package/promise
标签: javascript node.js mongodb asynchronous mongoose