Skip to content
Advertisement

Sqlite .all() function returns an undefined promise. How can I use the result further?

I am just starting to work with JS and SQLite. And could not find any help for my specific question.

I want to keep a return to use it as a foreign key in a second table. This is my function:

JavaScript

What do I have to do so that promise does not stay undefined outside of the function?

Rest of the code:

JavaScript

My other function just creat some strings and I run a few times db.run(…) to add some tables.

Advertisement

Answer

To put it more plainly, your getIdByName function never returns anything. You need to return the value you get back from await db.get(...). Once you do that, when you call getIdByName, you should get your response from the database.

You should also know that your code is susceptible to SQL injection, which is a major security vulnerability. Instead of concatenating a string, you should use a prepared statement.

JavaScript

Update: Promise Wrapper for SQLlite – Aug 1, 2020

Based on this blog post, it seems it’s not possible to do native async/await using sqlite3. However, you can write a wrapper function around db.all to return a promise, which will allow you to use async/await. Note the use of ? in the SQL statement, which will be replaced by the values of the array in the second argument following the same order. For more help with parameterized queries, read the params bullet point in the documentation here.

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement