我有三个组件A
,B
和C
。
当A
向B
发送HTTP请求时,B
会向C
发送另一个HTTP请求,检索相关内容并将其发送回A
,作为HTTP响应。
B
组件由以下Node.js代码段表示。
var requestify = require('requestify');
// sends an HTTP request to C and retrieves the response content
function remoterequest(url, data) {
var returnedvalue;
requestify.post(url, data).then(function(response) {
var body = response.getBody();
// TODO use body to send back to the client the number of expected outputs, by setting the returnedvalue variable
});
return returnedvalue;
}
// manages A's request
function manageanotherhttprequest() {
// [...]
var res = remoterequest(url, data);
// possible elaboration of res
return res;
}
由于body
功能,我需要返回remoterequest
个内容。
我注意到,目前,POST请求是异步的。因此,在将returnedvalue
变量返回给调用方法之前,永远不会分配它。
如何执行同步HTTP请求?
答案 0 :(得分:0)
您正在使用restify
,一旦调用其方法(promise
,post
等等),它将返回get
。但是,您创建的remoterequest
方法未返回promise
,您无法使用.then
等待。您可以使用promise
或内置async-await
返回promise
,如下所示:
使用承诺:
var requestify = require('requestify');
// sends an HTTP request to C and retrieves the response content
function remoterequest(url, data) {
var returnedvalue;
return new Promise((resolve) => {
requestify.post(url, data).then(function (response) {
var body = response.getBody();
// TODO use body to send back to the client the number of expected outputs, by setting the returnedvalue variable
});
// return at the end of processing
resolve(returnedvalue);
}).catch(err => {
console.log(err);
});
}
// manages A's request
function manageanotherhttprequest() {
remoterequest(url, data).then(res => {
return res;
});
}
使用async-await
var requestify = require('requestify');
// sends an HTTP request to C and retrieves the response content
async function remoterequest(url, data) {
try {
var returnedvalue;
var response = await requestify.post(url, data);
var body = response.getBody();
// TODO use body to send back to the client the number of expected outputs, by setting the returnedvalue variable
// return at the end of processing
return returnedvalue;
} catch (err) {
console.log(err);
};
}
// manages A's request
async function manageanotherhttprequest() {
var res = await remoterequest(url, data);
return res;
}