Sunday, 21 May 2017

NodeJS - Wait for response before returning value

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.



via Egee

No comments:

Post a Comment