0

I'm working on a node project with sqlite as my db.

function select_from_table(tablename, limit) {

  let arr = [];
  let sql = `SELECT id FROM ${tablename} WHERE Type='Real' LIMIT ${limit}`;
   db.each(sql, function (err, row) {
    console.log(row.PropertyId);
    arr.push(row.PropertyId);
  });
  return arr;
}

when I ran:

console.log(select_from_table('myData', 4));

I get '[]'

stepping through this I see that control goes right to return array and then goes back to the loop above to perform the select, so that the arr is never returned. I then tried:

async function select_from_table(tablename, limit) {

  let arr = [];
  let sql = `SELECT id FROM ${tablename} WHERE Type='Real' LIMIT ${limit}`;
   await db.each(sql, function (err, row) {
    console.log(row.PropertyId);
    arr.push(row.PropertyId);
  });
  return await arr;
}

but this returns a promise. What's the best way to approach returning the selected result?

user1592380
  • 34,265
  • 92
  • 284
  • 515
  • You cannot synchronously access an asynchronous result: there's no way to make the caller block. You will have to deal with the returned promise in the calling code. – Jared Smith Jan 01 '21 at 16:55
  • Is this the usual approach in node? – user1592380 Jan 01 '21 at 17:31
  • Yes. There are basically only two approaches to dealing with asynchrony in JS: callbacks and Promises (async/await is just syntactic sugar over Promises, which is why your async function implicitly returns one). While you can build other stuff like CSP on top of them, those are the constructs the language gives you. – Jared Smith Jan 01 '21 at 17:44

0 Answers0