1

I want to construct an object using map. I am firing sql query inside of map function, but when i send the final map array it is giving null value.

    var result = rows.map((uod) => {
      UserOrder.findOne("id", uod.userorderid).then((userorder) => {
        uod.userorder = userorder
        return uod
      })
    })
    res.send(result)

I want the function to return the main object with "userorder" object as key value pair. But it is returning [null,null....]

ADITYA HAZARIKA
  • 300
  • 1
  • 4
  • 13
  • You're never returning to your `map` callback method, instead, you are returning to your promise's `.then()` callback method – Nick Parsons Sep 16 '19 at 10:13
  • Not `null`, `undefined`. – T.J. Crowder Sep 16 '19 at 10:15
  • 1
    Your code has two unrelated problems, [this one](https://stackoverflow.com/questions/45754957/why-doesnt-my-arrow-function-return-a-value) and [this one](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call). To fix it, you need to do this: `Promise.all(rows.map(uod => UserOrder.findOne("id", uod.userorderid))).then(orders => { res.send(orders); }).catch(error => { /*...handle/report error...*/});`. Note that that will fail if **any** of the `findOne` calls fails. If you want to return the ones that succeeded instead, use `allSettled`. – T.J. Crowder Sep 16 '19 at 10:17
  • 1
    One possible `allSettled` version: `Promise.allSettled(rows.map(uod => UserOrder.findOne("id", uod.userorderid))) .then(results => { res.send(results.filter(result => result.status === "fulfilled").map(result => result.value)); return results; }) .then(results => { const failed = results.filter(result => result.status !== "fulfilled"); if (failed.length) { /*...handle/report the fact some failed...*/ } });` – T.J. Crowder Sep 16 '19 at 10:21

0 Answers0