返回对nodejs中调用函数的html响应

时间:2018-04-27 11:50:43

标签: javascript node.js httprequest requestify

我有这个Node.js片段。

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;
}

我需要将res内容而不是true返回给来电者。

我该怎么做? 在这种情况下,requestify的方法是异步的,因此,无法检索返回的值(因为它尚未生成)。 我该如何解决?如何发送同步HTTP POST请求(即使没有requestify)?

2 个答案:

答案 0 :(得分:0)

你需要返回一个promise并在remoteRequest返回的promise的then方法中使用它:

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...
});

请注意,它仍然不会成为同步POST,但您可以在可用时使用response.getBody(),如果这是您想要的

答案 1 :(得分:0)

您可以参考此讨论,了解如何使用从承诺How do I return the response from an asynchronous call?

返回的内容

正如@Logar所提到的,您不能直接使用您的承诺中返回的内容。您必须先调用您的方法返回一个承诺,并使用.then使返回的内容可用。

实施例

    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
        });

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 });