如何使用 async.js 同步运行这个简单的Node.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... 将发布 ID 分配给 id 变量的代码,然后运行返回 ID。

我已经尽力了,但我不知道该怎么做。有什么办法可以做到这一点吗?(是否使用异步.js(

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

所以你这里的代码将看起来像:

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

您可以使用承诺。

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*/})

最新更新