Home > Enterprise >  promise sql in js
promise sql in js

Time:10-07

my task is so that I can get the result of the message variable, but I get only the following result in the console: result [object Promise]

async function Testing() {
  let rest = await new Promise((res, rejects) => {
    db.query("SELECT * FROM `nitrоboost`", (error, row) => {
      if (error) {
        console.log(error);
      }
    });
  });
  return rest;
}
let message = Testing();
console.log(`result`   message);

CodePudding user response:

The Testing function is asynchronous, so it will always return a Promise.

You'll need to use the await syntax or .then() to access the value of a Promise.

Also, we need to pass the query result to the res callback so we can get the output:

// Mock db object for illustration... 
const db = { 
    query(sql, cb) {
        console.log('Running query:', sql);
        setTimeout(() => cb(null, [{ id: 1, data: 'some data' }]), 500)
    }
}


async function Testing() {
  return new Promise((res, rejects) => {
    db.query("SELECT * FROM `nitrоboost`", (error, row) => {
      if (error) {
        console.log(error);
        // Pass the error to the rejects callback
        rejects(error);
      } else {
        // Pass the result to the res callback
        res(row)
      }
    });
  });
}

async function runTesting() {
    let message = await Testing();
    console.log(`result:`,  message);
}

runTesting();
    
.as-console-wrapper { max-height: 100% !important; top: 0; }

  • Related