0

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)?

Auron
  • 51
  • 5

2 Answers2

1

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

Logar
  • 1,248
  • 9
  • 17
0

You can refer to this discussion about how to use content returned from a promise How do I return the response from an asynchronous call?

As mentionned by @Logar, you can't use directly the content returned in your promise. You must call your method returning a promise first, and use .then to make the returned content available.

Example:

    var requestify = require('requestify');
    // [...]
    // This function returns a promise, so you have to call it followed by `.then` to be able to use its returned content
    function remoterequest(url, data) {
        requestify
            .post(url, data)
            .then((response) => {
                return response.getBody();
            });
    }
    //....
    //... Some other code here
    //....

    // Make a call to your function returning the promise
    remoterequest('your-url-here', {data-to-pass-as-param})
        .then((res) => { // Calling `.then` here to access the returned content from `remoterequest` function
            // Now you can use `res` content here
        });

A. Maitre
  • 2,985
  • 21
  • 25