javascript - Node.js 等待异步函数完成,然后继续执行其余代码

标签 javascript node.js mongodb asynchronous mongoose

在我的代码中,我有 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 个循环结束然后继续,但由于显而易见的原因,我不能将其余代码放在循环中!有没有什么办法解决这一问题?谢谢!

最佳答案

您可以使用回调,但我更喜欢 promises,因为它们很优雅。

利用 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.

关于javascript - Node.js 等待异步函数完成,然后继续执行其余代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38058540/

相关文章:

java - Mongo 副本集 - 客户端是否需要了解所有这些?

javascript - 调用 db.<collection> 时 MongoDB 的隐式集合访问的工作

javascript - Mongoose - 双向引用

javascript - 如果程序的当前版本高于我的版本,如何显示 DIV?

node.js - 在 promise 链中调用 process.exit() 的正确位置

node.js - 在 Jade/Node.js 中过滤 Markdown 内容

javascript - 未捕获的语法错误 : Unexpected token < (from &lt;! DOCTYPE html>)

javascript - 无法在 onclick 事件上删除随机数组元素

javascript - 全屏 slider 在 Webkit 上卡顿,在 Firefox 上流畅

javascript - Angular JS - 重新加载整个页面