0

I need the id from mongoose before I continue

  let newReportId = await ReportService.create(report);
  console.log('new report id ', newReportId);

  let reportAsString = turnDataIntoHtmlString(report);
  return createJSReportPdf(reportAsString, newReportId, type);

Syntax wise this should be correct in this async function. Do not log newReportId until the service has returned.

However it is undefined and logs before the report service has done it's job even though I have stated AWAIT! ReportService.create(report) does log the id, but I can't return it.

  let id = await serviceReport.save((err, doc) => {
   if (err) {
    console.error(err);
   } else {
    console.log('doc cod ', doc._id);
   return doc._id;
 }
});

return id;

Please help!

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
godhar
  • 1,128
  • 1
  • 14
  • 34
  • @Neil Lunn can you please link the question that this is a duplicate of then? – godhar Mar 08 '19 at 02:55
  • The `await` keyword is for a `Promise` i.e `let { _id } = await serviceReport.save();`. What you have is using a "callback", which is a different thing. – Neil Lunn Mar 08 '19 at 02:55
  • Can you show more details on what library are you using, version of that library and related stuff like that? it's so limited details here. My suggest would be checking that `ReportService.create()` actually return something, if not u need to call from mongodb to get the data. – johnson lai Mar 08 '19 at 02:55
  • 1
    @johnsonlai Not necessary. This is using `mongoose` and all of it's methods natively return a `Promise`. Hence the duplicate in order to learn from. – Neil Lunn Mar 08 '19 at 02:56
  • If based on @NeilLunn statement, and you want to create async and await, you need to write a Promise wrapper. Check https://medium.freecodecamp.org/how-to-make-a-promise-out-of-a-callback-function-in-javascript-d8ec35d1f981 – johnson lai Mar 08 '19 at 02:57
  • @johnsonlai Read the first comment, and my response to you. Nothing to wrap here as it's already supported. Question done. – Neil Lunn Mar 08 '19 at 02:57
  • If you return a callback from an async call to the mongoose db, it must be wrapped in another promise then? It means that await keyword in front of the call to save() means nothing? This is odd. – godhar Mar 08 '19 at 03:04
  • Surely it must be common practice to want the id from the saved object for other parts of the flow. – godhar Mar 08 '19 at 03:06

0 Answers0