var UfcAPI = require('ufc-api');
var ufc = new UfcAPI({
version: '3'
});
const fighterId = [];
function getFighterId() {
ufc.fighters(function(err, res) {
for (let i = 0; i < res.body.length; i++) {
fighterId.push(res.body[i].id);
}
// console.log(fighterId);
})
};
function allFighters() {
for (let j = 0; j < fighterId.length; j++) {
request("http://ufc-data-api.ufc.com/api/v3/us/fighters/" + fighterId[j] + ".json", function(error, response, body) {
if (!error && response.statusCode === 200) {
console.log(JSON.parse(body));
}
})
}
};
第一个函数getFighterId()将通过json查看UFC名单上的所有战士。我捕获每个战斗机的所有ID并将其推送到fighterId数组。然后我想做一个循环查询战士与他们的身份,以获得每个战斗机更详细的信息。
我知道我需要完全填充数组然后运行我的第二个函数。我发现了有关promises和Async的信息,但对于如何实现它却非常困惑。
由于
答案 0 :(得分:0)
var UfcAPI = require('ufc-api');
var ufc = new UfcAPI({
version: '3'
});
function allFighters(fighterIds) {
fighterIds.forEach(fighterId => {
request("http://ufc-data-api.ufc.com/api/v3/us/fighters/" + fighterId + ".json", function(error, response, body) {
if (!error && response.statusCode === 200) {
console.log(JSON.parse(body));
}
})
});
};
function getFighterId(){
return new Promise((resolve,reject)=>{
ufc.fighters((err,res)=>{
if(err) reject(err);
else resolve(res.body)
})
})
}
getFighterId()
.then((ufcData)=>ufcData.map((u)=>u.id))
.then((data)=>allFighters(data))
.catch((err)=>console.log(err));
Please try with this one I have implemented with Promises. it can be implemented in many more ways. Let me know if it helps you.