Search code examples
javascriptnode.jshttprequestrequestify

Return html response to calling function in nodejs


I've got this Node.js snippet.

var requestify = require('requestify');
// [...]
function remoterequest(url, data) {
  requestify.post(url, data).then(function(response) {
    var res = response.getBody();
    // TODO use res to send back to the client the number of expected outputs
  });
  return true;
}

I need to return res content instead of true, back to the caller.

How can I do that? In this case, the requestify's method is asyncronous, therefore, the returned value is not possible to be retrieved (since it's not generated yet). How can I solve it? How can I send a synchronous HTTP POST request (even without requestify)?


Solution

  • you need to return a promise and use it in the then method of the promised returned by remoteRequest :

    var requestify = require('requestify');
    // [...]
    function remoterequest(url, data) {
      return requestify
        .post(url, data)
        .then((response) => response.getBody());
    }
    
    //....
    
    remoteRequest('/foo', {bar: 'baz'}).then(res => {
      //Do something with res...
    });
    

    Note that it still won't be a synchronous POST though, but you will be able to use response.getBody() when available, If this is what you wanted