简体   繁体   English

如何在 NodeJS 中返回来自 function 的 Post 请求的响应?

[英]How to return the response of Post request from a function in NodeJS?

I have a function in my project that processes most of my API requests (see simplified draft below)我的项目中有一个 function 处理我的大部分 API 请求(见下面的简化草案)

function sendRequest(){

    var reqbody;
    var resp;

    reqbody = unimportantRandomFunction();

    request.post({
        headers: {  'content-type'  : 'application/xml',
                    'accept'        : 'application/xml'},
        url: process.env.APIURL,
        body: reqbody
    }, function(error, response, body){
        resp = convert.xml2js(body, {compact:true});
    });

    return resp;
}

The problem I am facing is that request.post is asynchronous and by the time I get the response, an undifined value has already been returned.我面临的问题是 request.post 是异步的,当我收到响应时,已经返回了一个未定义的值。 I tried experimenting with promises (something I am entirely new to) but obviously I can't place my return in a.then block either because that return will not belong to the sendRequest function (correct me if I'm wrong).我尝试尝试使用 promises(这是我完全陌生的东西)但显然我不能将我的 return 放在 a.then 块中,因为该 return 不属于 sendRequest function(如果我错了请纠正我)。 Any ideas where I could put my return statement to make it work, that is wait for the value of "resp" to be assigned?有什么想法可以让我的 return 语句生效,那就是等待分配“resp”的值?

How about this modification?这个改装怎么样? Please think of this as just one of several possible answers.请将此视为几个可能的答案之一。

Promise is used sendRequest() . Promise 用于sendRequest() And the response value is retrieved in the async function. At the following modified script, at first sample() is run.并在异步 function 中检索响应值。在以下修改后的脚本中,首先运行sample() And sendRequest() is run, then the response value is retrieved at console.log(res) .并运行sendRequest() ,然后在console.log(res)检索响应值。

Modified script:修改脚本:

function sendRequest() {
  return new Promise((resolve, reject) => {
    var reqbody;
    var resp;

    reqbody = unimportantRandomFunction();

    request.post(
      {
        headers: {
          "content-type": "application/xml",
          accept: "application/xml"
        },
        url: process.env.APIURL,
        body: reqbody
      },
      function(error, response, body) {
        if (error) reject(error);
        resp = convert.xml2js(body, { compact: true });
        resolve(resp);
      }
    );
  });
}

async function sample() {
  const res = await sendRequest().catch(err => console.log(err));
  console.log(res);
}

sample();  // This function is run.

References:参考:

If I misunderstood your question and this was not the direction you want, I apologize.如果我误解了您的问题并且这不是您想要的方向,我深表歉意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM