Ad

Node Callback - Why Is This Not Working?

- 1 answer

I am currently trying to understand Node and callbacks, and have tried various solutions to this code in order to get it to work, however param2 is coming back undefined. Can anybody tell me why? And how to fix this? Thanks!

function getPage(callback) {

  url = 'http://www.google.com';

  if (url) {
    url = url;
  } else {
    console.log('There was an error. No URL submitted');
  }

  callback(url, param2);
}

function CB(url, param2) {
console.log(`The URL of the page requested was ${url} and the added argument          was ${param2}`);
}

 getPage(CB);
Ad

Answer

That's because param2is undefined in the scope where you are calling the callback function. To have param2 come back defined, make sure param2 is initialized in getpage()

function getPage(callback) {

  url = 'http://www.google.com';
  // **make sure param2 is defined**
  var param2 = "param2 value"

  if (url) {
    url = url;
  } else {
    console.log('There was an error. No URL submitted');
  }

  callback(url, param2);
}

function CB(url, param2) {
console.log(`The URL of the page requested was ${url} and the added argument was ${param2}`);
}

 getPage(CB);
Ad
source: stackoverflow.com
Ad