I need to fetch the data from two different API endpoints, and after both data is fetched I should do something with those data (ie. compare the data from two sources).
I know how to fetch the data from one API, and then call the callback function to do something with the data. I am doing this as follows.
function getJSON(options, cb) {
http.request(options, function(res){
var body = "";
res.on("data", function(chunk){
body += chunk;
});
res.on("end", function(){
var result = JSON.parse(body);
cb(null, result);
});
res.on("error", cb);
})
.on("error", cb)
.end();
}
var options = {
host: "api.mydata1.org",
port: 8080,
path: "/data/users/3",
method: "GET"
}
getJSON(options, function(err, result) {
if (err) {
return console.log("Error getting response: ", err);
}
// do something with the data
});
Now, what I would want to have something like:
var options2 = {
host: "api.mydata2.org",
port: 8080,
path: "/otherdata/users/3",
method: "GET"
}
Those would be the options to connect to the other API, and have a single callback function that would get called whenever the data from both APIs is loaded. How can I do that?
答案 0 :(得分:0)
我建议使用request-promise
模块返回表示异步操作的promises,然后您可以使用Promise.all()
跟踪它们何时完成,然后访问它们的结果:
const rp = require('request-promise');
function getJSON(options) {
return rp(options).then(body => {
return JSON.parse(body);
});
}
let options1 = {
host: "api.mydata1.org",
port: 8080,
path: "/data/users/3",
method: "GET"
};
let options2 = {
host: "api.mydata2.org",
port: 8080,
path: "/otherdata/users/3",
method: "GET"
};
Promise.all([getJSON(options1), getJSON(options2)]).then(results => {
// process results here
console.log(results[0]); // from options1 request
console.log(results[1]); // from options2 request
}).catch(err => {
// process error here
console.log(err);
});
您可以阅读Promise.all()
on MDN。网上有很多关于承诺的文章和教程。这是one。它们是ES6 Javascript的标准配置,并且已经在ES5中通过库提供多年。它们是Javascript语言中用于管理或协调异步操作的选定方案。如果您在Javascript中进行任何异步编程(几乎所有node.js编程都可以),那么您应该学习承诺。