Search code examples
javascriptmysqlnode.jsreturnundefined

Node.js request.post return undefined


I'm trying to return the body of a post request of another site in node.js, but the function below doesn't return anything

  // returns "undefined"
  mysqlVerify = (socialclub_id, session_id) => {
      request({
          url: 'http://myapi.site/VerifyUser',
          method: 'post',
          form: {
            socialclub_id: socialclub_id,
            session_id: session_id
          }
      }, (error, response, body) => {
          if(error) {
              return false       // this isnt returning
          } else {
              console.log(response.statusCode, body)
              return body == "1" // this isnt returning
          }
      })
  }

The other site is receiving the post request, and I am also getting the right body back when I use console.log, but the return just doesn't work. What am I doing wrong?


Solution

  • You can't use return inside a callback to return a value when your function is called. You could pass mysqlVerify a callback (a function which is run once the result is determined) and call it once you get a response, like so:

    mysqlVerify = (socialclub_id, session_id, callback) => {
        request({
            url: 'http://myapi.site/VerifyUser',
            method: 'post',
            form: {
                socialclub_id: socialclub_id,
                session_id: session_id
            }
        }, (error, response, body) => {
            if(error) {
                callback(false)       // call the function if false
            } else {
                console.log(response.statusCode, body)
                callback(body == "1") // call the function if condition met
            }
        });
    }
    

    The callback function can then do whatever you need with the result of mysqlVerify.