首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >返回对nodejs中调用函数的html响应

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

Stack Overflow用户
提问于 2018-04-27 11:50:43
回答 2查看 639关注 0票数 0

我有这个Node.js片段。

代码语言:javascript
复制
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请求(即使没有requestify)?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-04-27 12:12:58

您需要返回一个承诺,并在remoteRequest返回的承诺的方法中使用它:

代码语言:javascript
复制
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...
});

请注意,它仍然不是一个同步发布,但如果这是您想要的,则可以在可用时使用response.getBody()。

票数 1
EN

Stack Overflow用户

发布于 2018-04-27 12:48:43

您可以参考关于如何使用承诺How do I return the response from an asynchronous call?返回的内容的讨论。

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

示例

代码语言:javascript
复制
    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
        });

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50061810

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档