-2

I am trying to get image name from database but the function keeps returning undefined

const returnOldFileName = (id) => {
  let imageName;
  const getQuery = `SELECT image from products WHERE id=${id}`;
  db.query(getQuery, (err, result) => {
    console.log(result.rows[0].image);  // getting result here
    if (result) return result.rows[0].image;
  });
};

const image=returnOldFileName(2)
console.log(image) // undefined

1 Answers1

0
db.query(getQuery, (err, result) => {
    console.log(result.rows[0].image);  // getting result here
    if (result) return result.rows[0].image;
});

has a function within it:

(err, result) => {
    console.log(result.rows[0].image);  // getting result here
    if (result) return result.rows[0].image;
});

You are really returning to this function.

The easiest solution would be to make this syrchronous---but this is not recommended, which you can find a method for here.

You can also forgo the return statement, and include the query wherever you need it.

Ank i zle
  • 2,089
  • 3
  • 14
  • 36