0

So basically I am trying to make a function in javascript that fetches data from my SQLite database. This function is eventually supposed to be exported and used in another script, which will run the function with different SQL querys and send out the results to my web page.

import sqlite3 from "sqlite3";

const db = new sqlite3.Database(
  "path/to/my/db.db"
);


function getContent(sqlQuery, whenloaded) {
  return new Promise((resolve) => {
    resolve(
      db.all(sqlQuery, [], (err, rows) => {
        if (err) {
          console.log("Something went wrong in the db");
        } else {
          rows.forEach((row) => {
            whenloaded(row.page_content);
          });
        }
      })
    );
  });
}

async function showContent(sqlQuery) {
  await getContent(sqlQuery, (result) => {
    return result;
  });
}

console.log(
  showContent(`SELECT page_content FROM fruit WHERE page_name = "apples"`)
);

Console log being: Promise { <pending> }

Since this function seems to need to be an async one, because of the database being involved, I have tried the code above, which didn´t work. I have had the code below as a reference since I don´t have any prior experience of async functions.

function square(a, b) {
  return new Promise((resolve) => {
    resolve(a + b);
  });
}
async function output(a, b) {
  const ans = await square(a, b);
  console.log(ans);
}
output(10, 20);

I´ve seen a bunch of async function-related questions on here, even some with a db involved like in my case, but it´s just not exactly like mine and I´m not clever enough to implement their solutions in my own project. :)

  • There are a few issues I can see here. First of all - you are not resolving your promise anywhere in your `getContent` function. Second thing is that `forEach` method does not return anything so you can't use it to return rows from the db. – AbsoluteZero Nov 25 '22 at 10:14
  • `new Promise` requires a callback function (that takes two arguments) ... see how your "reference code" is written? – Jaromanda X Nov 25 '22 at 10:22
  • Does this answer your question? [How do I convert an existing callback API to promises?](https://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises) – derpirscher Nov 25 '22 at 10:25
  • I´ve tried to change my code and have updated the question with the new one. As you can see I get the content in one place, but not outside of that. Any tips? – Pontus Olsson Nov 25 '22 at 10:59

0 Answers0