0

I have this if function,

if (shorturl) {
 ...
    link.shorten({longUrl:"http://google.com"}, function(err, results) {
       return results;
    });
return results;
}

Now, I want the second return statement to receive the value of "results". Rather, I get "ReferenceError: results is not defined".

Help me nest the return/callback.

Reference:
I am trying to use http://github.com/nkirby/node-bitlyapi inside a function to get a shorturl

crlf
  • 13
  • 1
  • 3

2 Answers2

0

I assume you get the error with the second return results; line.

This looks like asynchronous code (using callbacks to execute some part of the code later in time), so you cannot just return a value from it and expect it to be available in the same execution frame.

The best way to handle your case is probably to execute the rest of the code inside the callback itself.

mdziekon
  • 3,531
  • 3
  • 22
  • 32
0

You cannot so this since link.shorten is asynchronous and that is why you provided a callback function to it. At the time the second return is evaluated results is undefined since the call to the link.shorten function has not returned yet.

You should wait for the callback and only then return the result or you can use promises and return a promise for the result. (There are a couple of different promise libraries for node).

https://howtonode.org/promises

Nitzo
  • 79
  • 6
  • thanks. When you say "wait for the callback" - what does that mean? I have the right answer in the 1st results. Now, how can I move it outside the scope of link.shorten? – crlf Sep 04 '16 at 13:37
  • You cannot since you have already performed the second return when you get the results. You need to plan your code accordingly. Either you return the result asynchronously with a callback or you return a promise from your function and not the result itself. If you post the calling code I might be able to help more. – Nitzo Sep 04 '16 at 14:19
  • I am trying to use https://github.com/nkirby/node-bitlyapi inside a function to get a shorturl. – crlf Sep 04 '16 at 15:26
  • Then when calling Bitly.shorten you should do something like : `function GetUrl(callback) { if (shortUrl) { link.shorten({longUrl:"http://google.com"}, function(err, results) { return callback(err, results); }); } else { return callback(null, results); }` – Nitzo Sep 04 '16 at 15:52