-1

Should be a simple problem but I cannot find a solution for it.

I'm working with an asynchronous messaging bot. For this use case, the bot is reacting to an event where it calls out to a Restful API and responds with a url. Here is the message.reply function call

message.reply(getUrl())

The getUrl implementation is this:

let url
request.get('http://thecatapi.com/api/images/get?format=src&type=jpg', 
function () {
  url = this.href
})
return url

Obviously what will happen is that the getUrl() function call will initially return undefined because it is not waiting for the request to finish.. But that's the problem - I cannot figure out how to make it wait for the request to finish before returning the value.

Egee
  • 67
  • 2
  • 7
  • Async! Rather than `message.reply(getUrl())` you want to be thinking `getUrl(message.reply)` – James May 21 '17 at 22:09
  • Neither of these answers are applicable because ``message.reply`` requires a parameter, specifically the return value for ``getUrl()``. For example, call it like ``getUrl(message.reply)``, nothing happens because no parameters are being passed to ``message.reply`` – Egee May 22 '17 at 03:47

1 Answers1

0

Update - I figured out I needed to change the implementation of the getUrl() function to be like this:

getUrl(callback)
request.get('http://thecatapi.com/api/images/get?format=src&type=jpg', 
function () {
  callback(this.href)
})

Hope this helps someone!

Egee
  • 67
  • 2
  • 7