node.jsnode-sqlite3

node sqlite return undefined although the data is inserted


I am try to insert data into sqlite3 database. The data is inserted but i get undefined as the return message instead of 'success'.

static async insert(firstname,lastname,username,role,phone,password,date) {
    const save_user = await db.run(
        ` INSERT INTO users
         VALUES(?,?,?,?,?,?,?,?) `,
        [this.lastID, firstname, lastname, username, role, phone, password, date],
        function (err) {
            if (err) {
                return {error:'error message'};
            }
            return {message:'success'};
        }
    );
return save_user
}

Solution

  • Assuming that you're using this sqlite3 package: this doesn't actually support promises, so you have to wrap db.run() manually:

    static async insert(firstname,lastname,username,role,phone,password,date) {
      const save_user = await new Promise(resolve => {
        db.run(..., err => {
          if (err) {
            resolve({ error : 'error message' });
          } else {
            resolve({ message : 'success' });
          }
        });
      });
      return save_user;
    }