Node.js等到asynchronous函数完成,然后继续执行其余的代码

在我的代码中,我有2个for循环执行一个asynchronous函数(在两个循环中它是相同的函数),但是在这两个循环之后的代码必须等到执行它们之后才运行。 这是我的代码:

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 

如果我运行的代码,我看到3(从console.log函数)之前,我看到1。但正如我所述,我必须等待循环结束前继续前进。 findVideo()函数只包含由mongoose提供的Video.find({})方法,然后返回值thumbnailPath和videoName。 我需要做的是等待2个循环结束,然后继续,但是由于显而易见的原因,我不能在循环中留下其余的代码! 有没有什么办法解决这一问题? 谢谢!

你可以使用callback,但我更喜欢承诺,因为它们是优雅的。

使用Promise.all() https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

 function getVideo(id){ return new Promise(function(resolve, reject){ findVideo(id, function(thumbnailPath, videoName){ resolve({ name: videoName, thumbnail: thumbnailPath }); }); }); } var promises = videoIds.map(function(videoId){ return getVideo(videoId); }); //callback in then section will be executed will all promises will be resolved //and data from all promises will be passed to then callback in form ao array. Promise.all(promises).then(function(data){ console.log(data); }); // Same for other list of tasks. 

最简单的解决scheme就是使用callback。 只是把你的循环包装在一个函数中,并做这样的事情。

 function findVid(callback) { 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'); if (callback) callback(); //This will be called once it has returned }); } } } findVid(function(){ //this will be run after findVid is finished. console.log('3'); // Rest of your code here. }); 

你可以使用Promise风格来代替callback,但是两者都有工作。 为了更多地了解callback和承诺,我find了一个很好的文章,将更详细地解释一切: http : //sporto.github.io/blog/2012/12/09/callbacks-listeners-promises/