我需要发出两个 http 请求,我希望将其放在两个单独的函数中。我同步想到:
..发出第一个http请求并返回响应
.. 将响应传递给第二个函数,从而发出第二个 http 请求
这里是第一个函数:
function getObjTypes(cfg) {
// request-options
var post_options = {
host: cfg.apiHost,
port: cfg.apiPort
};
// request
var ObjectTypes = [];
var post_req = http.request(post_options, function(res) {
res.setEncoding('utf8');
let resBody = '';
res.on('data', function (chunk) {
resBody += chunk;
});
res.on("end", () => {
var resObject = JSON.parse(resBody);
return ObjectTypes; // Here the ObjectTyes needs to be passed as a return
});
});
post_req.end();
}
我知道出了什么问题..http请求是异步的,因此在第一个函数的响应之前调用第二个函数..但是我如何“修复”这个问题?
由于某种原因想要避免 Promise 或 async
/await
,那么
sync-request-curl可能会有所帮助。。
sync-request 中功能的子集,但利用 node-libcurl 在 NodeJS 中获得更好的性能。
这是 GET 请求的基本用例:
// import request from 'sync-request-curl';
const request = require('sync-request-curl');
const response = request('GET', 'https://ipinfo.io/json');
console.log('Status Code:', response.statusCode);
console.log('body:', response.body.toString());
具体到您的情况,当以同步方式完成时,它可能看起来像:
const request = require('sync-request-curl');
function getObjTypes(cfg) {
// request-options
const post_options = {
host: cfg.apiHost,
port: cfg.apiPort,
};
// Make a synchronous HTTP request
const res = request('POST', `http://${post_options.host}:${post_options.port}`);
if (res.statusCode === 200) {
const resBody = res.body.toString();
const jsonObject = JSON.parse(resBody);
return jsonObject;
} else {
// handle error
}
}
sync-request-curl 在性能方面与异步等效项(例如 then-request)相当,不过,我再次建议重新考虑 Promise 或 async
/
await
(如果您的要求允许)。希望这有帮助:)。