Peter Pik
Peter Pik

Reputation: 11193

Request callback with node

I'm trying to create a callback function, but keep getting told that data is not a function. I've set it up according to another question, but does not seem to work?

getRequest("http://", function(error, data){
  console.log(data);
});

function getRequest(url, error, data) {
  request({
      method: 'GET',
      uri: url,
      headers: {
        'Content-Type': 'application/json',
        'dataType': 'json'}
    }, function (error, response, body){
      if(!error && response.statusCode == 200){

        data(JSON.parse(body));

      } else {
        error(error);
      }
    })
}

Upvotes: 0

Views: 2198

Answers (1)

G07cha
G07cha

Reputation: 4164

In case if you want to proceed both, success and failure result in one callback you should replace calling data with cb(or error as was in your code.

getRequest("http://", function(error, data){
  if(error) throw error
  console.log(data)
});

function getRequest(url, cb, data) {
  request({
      method: 'GET',
      uri: url,
      headers: {
        'Content-Type': 'application/json',
        'dataType': 'json'}
    }, function (error, response, body){
      if(cb) {
          cb(error, JSON.parse(body))
      }
    })
}

Otherwise, you should check if both callbacks provided

function getRequest(url, success, error) {
  request({
      method: 'GET',
      uri: url,
      headers: {
        'Content-Type': 'application/json',
        'dataType': 'json'}
    }, function (error, response, body){
      if(error && failure) {
         failure(error)
      } else if(success) {
         success(JSON.parse(body))
      }
    })
}

In this case, you should provide two callback functions, first for success result and a second one for error which is less common pattern.

Upvotes: 1

Related Questions