-1

This code returns undefined when it should be data from the Database. It is part of a class which has the variable this.database (an sqlite3 database). What have I done wrong?

    getData(chip_id) {
            let user_name;
            this.database.get("SELECT data FROM chips WHERE id=?",[chip_id],(err,row) => {
                    user_name = row.data;
            });
            return user_name;
    }
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – CertainPerformance Apr 11 '20 at 11:28

1 Answers1

-1

Retrieving data from database is an asynchronous action and you should handle it with something like Promise or async function. Change your function to this.

getData(chip_id) {
  return new Promise((resolve, reject) => {
    let user_name;
    this.database.get("SELECT data FROM chips WHERE id=?", [chip_id], (err, row) => {
      if(err) {
        reject(err);
      }
      else {
        user_name = row.data;
        resolve(user_name);
      }
    });
  });
}

and in the client side:

getData(id)
  .then(username => {
    // the username is ready to use
  })
  .catch(error => {
    // handle the error
  });

Reading these links also helps you a lot to start:

Callbacks Vs Promises and basics of JS

Getting to know asynchronous JavaScript: Callbacks, Promises and Async/Await

Converting callbacks to promises

Saeed
  • 5,413
  • 3
  • 26
  • 40