0

I am new to Nodejs and javascript and working on nodejs api code. I am using GandiAPI to check domainAvaliablity(Project related requirement) and have created a get request method (checkDomainAvaliablity) like this.

  exports.checkDomainAvaliablity = function (req, res) {
  gandiApi.methodCall('domain.available', [gandiapikey, [domain]], callback)      
  };

And I have a callback function which have 2 parameters(which I can not change). I am able to get the value succesfully in my callback function. Now I want to return "value" from callback and want to set in "res" paramameter of checkDomainAvaliablity function(Parent function) (something like res.json(task)) .

 var callback = function (error, value) {

   console.dir(value)
   if (value[domain] == 'pending') {
   console.log('result is not yet ready')
   setTimeout(function () {
   gandiApi.methodCall('domain.available', [gandiapikey, [domain]],
   callback)
   }, 700)
   }
   else {
    console.dir(value)
   }


   // I want to return "value" from here and want to set in "res"  paramameter of checkDomainAvaliablity function (Parent function).
 } 

Note: Use of callbackfuncion is neccessary.

Nimish goel
  • 2,561
  • 6
  • 27
  • 42
  • 1
    Can you explain how it is useful to you to store the result in `res`, when the outer function that got `res` passed as argument has already completed its execution at the time the callback is invoked? Why not use a new variable? – trincot Jul 09 '17 at 18:07
  • I need to return something from get method as result in json format. – Nimish goel Jul 09 '17 at 18:10
  • 1
    You can not return something from the get method, since it already returned by the time the callback is called. Maybe you could get some clarification by reading up on asynchronous callback functions. See also: http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – trincot Jul 09 '17 at 18:14
  • checkDomainAvaliablity is my get method and I want to set in res parameter (something like **res.json(task)**) – Nimish goel Jul 09 '17 at 18:17

1 Answers1

0

Thanks @trincot. Putting the callback function inside the parent function works fine.

exports.checkDomainAvaliablity = function (req, res) {
  domain = req.params.domainAvaliablity
  var callback = function (error, value) {
    console.log("logging" + value + error)
    if (value[domain] == 'pending') {
      console.log('result is not yet ready')
      setTimeout(function () {
        gandiApi.methodCall('domain.available', [gandiapikey, [domain]],
          callback)
      }, 700)
    }
    else {
      res.send(value);
      console.dir(value)
    }
    
  }

  gandiApi.methodCall('domain.available', [gandiapikey, [domain]], callback)
  
};
Nimish goel
  • 2,561
  • 6
  • 27
  • 42