-1

I am trying to get the result back from function where the result is in the callback. However the result always come back as undefined even though I set it to be the res. Can someone explain why this does not work?

function getData(id, callback) {
  return dataModel.findOne({ id }).exec((err, res) => {
    if (err) return callback(err)
    return callback(null, res)
  })
}

async function middleware(req.body) {
  try {
    let result
    await getData(req.body, (err, res) => {
      if (err) throw err
      result = res
    })
    await nextFunc(result)...  // result is undefined
  } catch (err) {
    console.log(err)
  }
}
Bev01
  • 11
  • 2
  • 1
    `getData` doesn't return a promise, so `await`-ing it is not going to do much. You can [convert it to a promise](https://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises). EDIT: seems like [you just omit the callback](https://mongoosejs.com/docs/promises.html#queries-are-thenable) and you'd get a promise-like – VLAZ May 13 '21 at 19:39
  • 1
    Mixing callbacks with `await` is a red flag. `await` can only work as you expect if you are working with promises, in which case you wouldn't need a callback. – Felix Kling May 13 '21 at 19:43
  • 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) – Jared Smith May 13 '21 at 19:45

2 Answers2

0

You are using callbacks, but in order to make things work with async await you are supposed to use promises

devnull69
  • 16,402
  • 8
  • 50
  • 61
0

Try

function getData(id, callback) {
  return new Promise((resolve, reject) => {
    dataModel.findOne({ id }).exec((err, res) => {
      if (err) reject(err);
      resolve(res);
    });
  });
}


async function middleware(req.body) {
  try {
    let result = await getData(req.body);
    await nextFunc(result);
  } catch (err) {
    console.log(err);
  }
}
Nafis Islam
  • 1,483
  • 1
  • 14
  • 34
  • Thanks!!! This did the trick. Can I ask, if there is an err, where does the reject(err) go to? Do I have to check on what is returned in the result or does the err just go straight into the catch block? – Bev01 May 13 '21 at 20:01
  • straight into the catch block @Bev01 – Nafis Islam May 13 '21 at 20:05