0

I want to receive an array from db.all function in order to use it in my custom JSON object that I want to return it as a response

I have tried Object.values(members); members.fulfillmentValue; some PROMISE methods I found in StackOverFlow

app.get('/group/:groupId', (req, res, next) => {

    const members= db.all('SELECT name,active FROM members WHERE groupId = ?;', req.params.groupId);

    return db.get('SELECT * FROM groups WHERE groups.id = ?;',req.params.groupId)
     .then(group =>  res.json({
         group.name,
         members:[members]
        }))
        .catch(next);
});

actual response

{
   "name":"group 1",
   "memebers":[
      {"isFulfilled":true,"isRejected":false,"fulfillmentValue":[
         {"name":"Member 1","active":1},
         {"name":"Member 2","active":0}
      ]
   }]
}

expected response

{
   "name":"group 1",
   "memebers":[
      {"name":"Member 1","active":1},
      {"name":"Member 2","active":0}
   ]
}
JAZWii
  • 47
  • 6
  • 1
    `db.all` (similar to `db.get`) is returning a Promise; you need to use a callback or a chained `.then(...)` to retrieve the result. Consider something like [`Promise.all(...)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all) so that you can run both queries and act upon the results when they've both completed. – Tyler Roper Oct 30 '19 at 20:53
  • 1
    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) – Aluan Haddad Oct 30 '19 at 21:13
  • thank you @TylerRoper I tried Promise all as in the link I got this error ``` TypeError: [object Object] is not iterable at Function.all () ``` Thank you @AluanHaddad I have tried several ones in the link you have sent me several return empty and several return errors – JAZWii Oct 31 '19 at 13:38

1 Answers1

0

I have solved it by adding async

app.get('/group/:groupId', async (req, res, next) => {

    const members= await db.all('SELECT name,active FROM members WHERE groupId = ?;', req.params.groupId).then();

    return db.get('SELECT * FROM groups WHERE groups.id = ?;',req.params.groupId)
     .then(group =>  res.json({
         group.name,
         members:members
        }))
        .catch(next);
});

thanks to all who tried to help

JAZWii
  • 47
  • 6