Louie Miranda
Louie Miranda

Reputation: 1159

Proper way to get the result of MySQL from Node.js function callback?

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

Upvotes: 0

Views: 34

Answers (1)

Yevhenii
Yevhenii

Reputation: 1713

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(/* ... */);
})

Upvotes: 2

Related Questions