如何使用async.js同步运行这个简单的node.js代码?

时间:2017-07-17 12:20:33

标签: node.js async.js

这是一个简单的函数,它将获取一个帖子网址并返回该网址的帖子ID。

function findPostIdByUrl (url) {

  var id;

  Post.findOne({url}, '_id', function (err, post) {
    if (err) throw err;
    id = post.id;
  });

  return id;
}

但它没有返回实际的id,因为它是异步运行的。我想先运行Post.fin ...代码,将post id分配给id变量,然后运行return id。

我已经尽了最大努力,但我还没弄明白我该怎么做。有没有办法实现这个目标?(无论是否使用async.js)

2 个答案:

答案 0 :(得分:2)

您可以在此处执行的操作是使用async / await

从您的请求中获取所有数据

所以这里的代码如下:

async function findPostIdByUrl (url) {
   var id;
   var post = await Post.findOne({url}, '_id')
   id = post.id
   return id;
}

答案 1 :(得分:0)

您可以使用Promises

function findPostIdByUrl (url) {
  var id;
  return Post.findOne({url}, '_id').then((post) => {
      id = post.id
      return id;
  })
  .catch((err) => {/* Do something with err */})
}

您实际上可以跳过设置ID。

return Post.findOne({url}, '_id').then((post) => {
   return post.id;
})

同时发布此帖子,findPostIdByUrl应该用作

findPostIdByUrl(url).then((id) => {/* Whatever you need to do with id*/})
相关问题