0

What is the proper way to get the result of this MySQL Query out of GetAllFarms and into a variable called err and farms? Sorry, doing a quick code try and coming from a different language.

var err, farms = GetAllFarms()
console.log("GetAllFarms:")
console.log(farms)
console.log(err)


function GetAllFarms(callback) {
    query = db.query("SELECT * FROM farms ", function (err, result) {
        console.log("DEBUG:QUERY//");
        console.log(query.sql);
        // console.log(result)

        if (err) {
            // console.log(err)
            return callback(err, null)
        } else {
            // console.log(result)
            return callback(null, result)
        }
    });

    // db.end()

    console.log("query")
    console.log(query.result)

    return query
}

Any help is much appreciated. Thanks

1 Answer 1

2

You have to decide wether you want to provide result via callback or with return. Don't mix them, it's confusable.

Callback approach

var err, farms = GetAllFarms()
console.log("GetAllFarms:")
console.log(farms)
console.log(err)


function GetAllFarms(callback) {
    query = db.query("SELECT * FROM farms ", function (err, result) {
        console.log("DEBUG:QUERY//");
        console.log(query.sql);
        // console.log(result)

        if (err) {
            // console.log(err)
            return callback(err, null)
        } else {
            // console.log(result)
            return callback(null, result)
        }
    });

    // db.end()

    console.log("query")
    console.log(query.result)
}

// usage
GetAllFarms((error, result) => {
    if (error) {
      // handle error
    }
    // process result
})

Promise approach

var err, farms = GetAllFarms()
console.log("GetAllFarms:")
console.log(farms)
console.log(err)


function GetAllFarms() {
    return new Promise((resolve, rejct) => {
    db.query("SELECT * FROM farms ", function (err, result) {
          console.log("DEBUG:QUERY//");
          console.log(query.sql);

          if (err) {
              return reject(err)
          } else {
              return resolve(result)
          }
      });
  });
}

// usage
(async () => {
  const res = await GetAllFarms();
  // or 
  GetAllFarms().then(/* ... */).catch(/* ... */);
})
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the recommendation. For the callback, what could be missing if the response was? TypeError: callback is not a function
It seems that you didn't provided callback function as a first argument of function, I have added callback approach example in first code snipped, please take a look.
Also make sure that you provide callable function (like this GetAllFarms(() => {})) and not result of some function (like this GetAllFarms(someFunc()))

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.