-1

My problem is with creating a database. It is created too late and causes problems with further queries. I tried to use async and await but it seems it doesn't solve the problem.

async function storeDailyDealToDB(dailyDeal) {
    const db = new sqlite3.Database('database.db');

    await new Promise((resolve) => {
        const QUERY_CREATE_TABLE =
            "CREATE TABLE IF NOT EXISTS daily_deal ( id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT,)";
        db.run(QUERY_CREATE_TABLE);
        resolve("done")
    });

    await new Promise((resolve) => {
        const insert =
            "INSERT INTO daily_deal (title) VALUES (?)";
        const stmt = db.prepare(insert);
        stmt.run([dailyDeal['title']]);
        stmt.finalize();
        resolve("done")
    });

    let lastRow = await new Promise((resolve) => {
        db.each("SELECT * FROM daily_deal ORDER BY id DESC LIMIT 1", function (err, row) {
            resolve(err == null ? {} : row)
        });
    });

    db.close();

    return lastRow
}

Here is the error I get:

[Error: SQLITE_ERROR: no such table: daily_deal
Emitted 'error' event on Statement instance at:
] {
  errno: 1,
  code: 'SQLITE_ERROR'
}

Node.js v17.9.0

I did a lot of research and I am stuck. I read to use Promise but it works partially. I am not sure how to tackle this problem.

1
  • That's not how you turn things into promises - you're still running the code synchronously, then resolving before the actual work happens. Node has nodejs.org/api/util.html#utilpromisifyoriginal in the box which can handle conventional patterns. You don't need new Promise very often. Commented Apr 16, 2022 at 7:57

1 Answer 1

0

After looking at the reference docs, of Database#run, you should pass a callback to the run method. Inside this callback, you want to either resolve or reject the promise depending on the outcome.

await Promise((res, rej) => {
    db.run(..., (err, result) => {
        if (err) rej(err) else res(result)
    });
});

I think this is correct (untested however).

Sign up to request clarification or add additional context in comments.

1 Comment

There is a missing new before Promise but yes, that's what I needed. Thanks for pointing me out the reference link.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.