繁体   English   中英

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

[英]How can I run this simple node.js code synchronously using 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)

您可以在这里执行的是使用async / await从请求中获取所有数据

因此您的代码如下所示:

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

您可以使用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*/})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM