0
var data = {};
data = connection.query(sql, [ori_image_path[i], src_image_path[i], title], function(err, results) {
  if (err) {
    console.dir(err);
    data["error_message"] = "failed";
    return data;
  }
})

if (i == ori_image_path.length - 1) {
  if (data["error_message"] === undefined) data["success_message"] = "이미지 업로드 완료";
  res.send(data);
}

I want to use variable data like this.

But variable data not changed!

always variable data = {}

I don't know javascript well...

How can I use variable data to detect errors? Could you help me?

1
  • connection.query is asynchronous, data does change but not when you want it to Commented May 19, 2021 at 15:51

1 Answer 1

1

Hello you need to set result to data in callback function like this

var data = {};
connection.query(sql, [ori_image_path[i], src_image_path[i], title], function(err, results){
    if(err){
        console.dir(err);
        data["error_message"] = "failed";
    }
    data = results;
    return data;
});

also you need to try

if(typeof data["error_message"] === 'undefined')

instead of

if(data["error_message"] === undefined)
Sign up to request clarification or add additional context in comments.

2 Comments

thank you, i want to variable data to use for detect error in sql execution, but variable data does not change. variable data is always = {} . In your code, can I set in variable data "error_message" and can i use this, outside of callback function?
Hi, I think you can't use, it's because Javascript running your if(typeof data["error_message"] === 'undefined') condition before data has property error_message. Method 1: Put everything in callback Method 2: Use await

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.