0

This is my code:

var itemData = [];
JSON.parse(row2['items']).forEach(async(item) => {
  sql = `SELECT * FROM \`items\` WHERE \`id\` = '${item}'`;
  db.get(sql, [], (err, row3) => {
    itemData.push(row3);
    console.log(itemData);
    console.log(1);
  });
  console.log(itemData);
  console.log(2);
});
console.log(itemData);
console.log(3);

And it outputs this (with DB response removed):

[]
2
[]
3
[
  {
    //row data was here
  }
]
1

I tried awaiting the forEach and the db.get, but nothing changed

  • 1
    `await` is not some pixie dust, you don't expect just to add it to the code to make it working in async way by magic or something. In particular, db.get doesn't seem to return a promise - it goes with callbacks instead. – raina77ow Oct 10 '20 at 13:33
  • @cbr it just partly solves the issue, the for loop is now working, but how can I wait for the db query to finish? – Martin Reicher Oct 10 '20 at 13:40
  • Does this help? [How do I convert an existing callback API to promises?](https://stackoverflow.com/q/22519784/996081) – cbr Oct 10 '20 at 13:41
  • @cbr it solved my problem, thanks – Martin Reicher Oct 10 '20 at 14:01

0 Answers0