0

I have an express api endpoint.

and my createS service like that:

async function createS(name, user_ids) {
    const seg = new Seg ({
        name : name,
        user_ids : user_ids
    })

      await seg.save().then(doc => {
          console.log(doc);===============>>> not undefined
          return {doc}
      }).catch(err => {console.log(err)});

}

And my controller like that:

async function createS(req,res,next){
    const sName = req.body.name;
    const user_ids = req.body.user_ids;
    console.log("*****")
    segService.createS(sName, user_ids).then(function (doc){
        console.log(doc)=============================================>>> undefined
    })

I know that this problem depends on asynchronous process. And I tried several type of solution Also Im new on Node JS.

Why Im getting this error? How can I solve this error?

akasaa
  • 1,282
  • 4
  • 13
  • 33
  • You're not returning anything from either `createS` function. Also, mixing `async/await` with `then` is a bad idea. – Heretic Monkey Apr 13 '21 at 13:52
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Heretic Monkey Apr 13 '21 at 13:53

1 Answers1

0

Your createS service needs to return a promise as opposed to the actual doc

Refactor your service to look like this

async function createS(name, user_ids) {
  const seg = new Seg ({
    name : name,
    user_ids : user_ids
  })

  return seg.save()
}
fortunee
  • 3,852
  • 2
  • 17
  • 29
  • It looks good, but. in this case in the controller you have to handle the error. And also you might leave the `async` – Peter Apr 13 '21 at 14:05
  • Thanks @Peter. Do you mind giving it an upvote? – fortunee Apr 13 '21 at 14:08
  • some error happend during your post edit. Im pasting it here: Controller error handling: async function createS(req,res,next){ const sName = req.body.name; const user_ids = req.body.user_ids; console.log("*****") try { const doc = await segService.createS(sName, user_ids) console.log(doc); } catch(err) { console.log(err) } } – Peter Apr 13 '21 at 14:13