4

I would like to get my data out from the sqlite db.each function using the promise object and the async/await I tried to do it but I don't really understand how to do it and I would like some explanations

my code below :

var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('./data.sqlite', (err) => {
    if (err) {
        console.error(err.message);
    }
    console.log('Connected to the database');
});

 function request (req) {
    new Promise(function (resolve, reject) {
        db.each(req, function (err, row) {
            if (err)
                reject(err);
            else
                data.push(row);
        }, function (err, n) {
            if (err) {
                reject(err);
            }
            else
                resolve(data);
        });
    });
}

data = await request("select * from user "); //I'm getting errors here 



db.close((err) => {
    if (err) {
        return console.error(err.message);
    }
    console.log('Close the database connection');
});
1
  • new Promise( -> return new Promise( Commented May 22, 2020 at 13:43

1 Answer 1

2

await can only be used inside an async function. Create an async function, inside this function, await the promise returned by request function

async function makeRequest() {
    data = await request("select * from user ");
}

and you need to return the promise from request function so that it can be awaited

function request (req) {
    return new Promise(function (resolve, reject) {
        // code
    });
}
Sign up to request clarification or add additional context in comments.

7 Comments

Thank you it works . By the way could you say me how to extract the data out from the functions to put them in a global variable .
you could define data outside of the makeRequest function
I tried this but I'm getting undefined at console.log(data) even after define it globally
you will get undefined because data variable is initialized after an asynchronous request. Log data inside makeRequest function after the await statement
But the my goal is to log it how the async function that is what I want since the beginning .I fought that the using of async/await will permit me to do this simply but it is the same as when I used promise .Do you have a method to have it outside async function
|

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.