我已经创建了一个调用http / https链接的服务。我能够成功调用http / https链接,但无法存储该链接返回的输出。我知道由于异步操作,这非常困难。如果有什么办法可以存储检索到的数据,请帮忙
下面是我的代码。我尝试创建一个全局变量,然后存储检索到的数据,但是它不起作用。
function apiCall(url, protocol) {
function externalApi(url, callback) {
try {
var https = $.require(protocol);
var request = https.request(url, function (response) {
var str = '';
var statusCode = response.statusCode;
var headers = response.headers;
response.on('data', function (data) {
str += data;
});
response.on('end', function () {
console.log("Data is " + str);
console.log("Status Code is " + statusCode);
console.log("Header is " + JSON.stringify(headers));
callback(str, statusCode);
});
});
request.on('error', function (e) {
console.log('Problem with request: ' + e.message);
console.log('Problem with request: ' + e);
});
request.end();
} catch (err) {
console.log("the error is" + err);
}
}
var status = function (data, statusCode) {
var callStatus = {};
if (statusCode == 200) {
callStatus.retrievedData = data;
callStatus.statusCode = statusCode;
callStatus.MESSAGE = "Successfully called";
}
console.log(callStatus);
};
externalApi(url, status);
}
预期结果将是返回检索到的数据或将检索到的数据存储在某些全局变量中的函数。现在,我可以对其进行控制台记录。请帮助
编辑:尝试将检索到的数据存储到回调中的变量中
function apiCall(url, protocol) {
function externalApi(url, callback) {
var output = '';
..........
........
......
console.log("Header is " + JSON.stringify(headers));
output = callback(str, statusCode);
});
});
...................
....................
return output;
...............
...............
var result = externalApi(url, status);
console.log("The result is " + result);
}
但是结果值为空。这是由于异步行为。如何解决这个问题。理想情况下,我希望函数apiCall返回结果。像下面这样
var result = externalApi(url, status);
return result;
}