0

This is a simple function which will get a post url and return the post id of that url.

function findPostIdByUrl (url) {

  var id;

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

  return id;
}

but it doesn't return the actual id, because it run asynchronously. I want to first run Post.fin... code which will assign the post id to the id variable, and then run return id.

I've tried my best but I didn't figure out how can I do that. Is there any way to accomplish that?(whether by using async.js or not)

2
  • I'm guessing promises/async-await can't be used? Commented Jul 17, 2017 at 12:28
  • I don't know how, I've search on the internet but I didn't find anything. Commented Jul 17, 2017 at 12:31

2 Answers 2

2

What you can do here is get all the data from your request using async/await

so your code here will look like:

async function findPostIdByUrl (url) {
   var id;
   var post = await Post.findOne({url}, '_id')
   id = post.id
   return id;
}
Sign up to request clarification or add additional context in comments.

7 Comments

It is not the valid code, when I run it I get: SyntaxError: Unexpected token function
can you post your function please?
and your node has to be v7.6 minimum or you cant use async/await (i m pretty sure its 7.6 but i m not 100% sure)
async function findPostIdByUrl (url) { var id; var post = await Post.findOne({url}, '_id') id = post.id return id; } var id = findPostIdByUrl('i-am-gonna-create-a-post'); console.log(id);
Oh I am using node 6.
|
0

You can use Promises.

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

You can actually skip setting the id.

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

Also Post this, findPostIdByUrl should be used as

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

2 Comments

It works but I want another thing. I want to be able to use the function like this: var id = findPostIdByUrl(url);
Unfortunately, Thats not how async works in JS. You can very well use the async solution below by @kikiwie. That would to an extent make it look like var id = await findPostIdByUrl(url); But be advised. thats just a syntactic sugar

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.