提供合作伙伴API后端,其中存储了未设置的对象及其信息。 我可以通过格式JSON的一个对象的api请求信息获取。 我的问题是我如何获得所有对象的所有信息。 以下代码用于获取一个对象的信息:
module.exports.getBackendData = function (request, response) {
var deviceid = request.params.id_device;
var id = request.params._id;
var points = [];
var optionsget = {
host: 'hostname', //here only the domain name
port: 443
, path: '/api/partner/' + id + '', //the rest of the url parameters if needed
method: 'GET', //do GET
auth: 'username:password'
};
var myRequest = https.request(optionsget, function (myResponse) {
var myData = '';
myResponse.on('data', function (d) {
myData += d;
});
myResponse.on('end', function () {
str = JSON.parse(myData);
var lat, long, statut, timestamp;
for (var i = 0; i <= str.reports.length - 1; i++) {
lat = str.reports[i].latitude;
long = str.reports[i].longitude;
timestamp = str.reports[i].ts;
statut = str.reports[i].move;
locations.push({
long: long
, latitude: lat
, move: statut
, timestamp: timestamp
});
}
response.json(points);
});
});
myRequest.end();
myRequest.on('error', function (e) {
console.error("error:", e);
});
}
由于api调用是异步完成的,我不知道如何获得所有对象的一次响应。
答案 0 :(得分:0)
这是一个经典的&#34;如何处理循环中的节点异步性质&#34;的问题。
查看库,如async
或steed
,Promises,Async / Await。
在任何情况下,如果我可以从您的问题中推断出这一点,那么您的"list of objects IDs"
就会丢失。
API的最佳性能和友好方式可能是逐个执行。
我去了
const steed = require('steed')()
const ids = [1, 2, 3]
function makeHttpRequest (id, cb) {
// as in your example
return locations
}
steed.mapSeries(ids, function (id, cb) {
makeHttpRequest(id, cb)
}, (err, result) => {
if (err) return console.log(err)
// result is an array of all the resutls of the single calls
console.log(result)
})