考虑以下函数:
function suggestSong(songs){
console.log("Suggesting song from songs:", songs);
var self = this;
var totalRelatedVideos = [];
var count = 0;
$.each(songs, function(){
count++;
self.getRelatedVideos(this.videoId, function(relatedVideos){
count--;
totalRelatedVideos = totalRelatedVideos.concat(relatedVideos);
});
});
var maxWaitTime = 1000;
var waitTime = 200;
var elapsedTime = 0;
var waitInterval = setInterval(function(){
elapsedTime += waitTime;
if(count == 0 || elapsedTime >= maxWaitTime){
clearInterval(waitInterval);
console.log("I found related videos: " + totalRelatedVideos.length);
}
}, waitTime );
};
这就是我目前实现在执行另一段代码之前等待异步事件集合完成的方式。不过,有很多代码要做的很少。我想知道是否有一种不那么钝的方法可以达到相同的结果?