-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
0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.