在使用API和Promise方面,我是一个很大的新手-因此,我很难解决这个问题。
目标是向API发出GET请求并返回这些结果。但是,由于API将数据分布在多个页面上,因此我将遍历API页面,直到返回0个列表。
我能够成功地将列表记录到控制台,但是,即使listsExist设置为false,loopThroughListings内部的while循环也似乎从未关闭。
我哪里出错了?
const axios = require('axios');
// Loop through multiple pages of listings in the API
function loopThroughListings() {
let listingsExist = true;
// Loop through listings until they don't exist
while(listingsExist) {
getListing().then(function(listing) {
if(listing.length < 1 ) {
// if listings don't exist, stop the loop
// THIS IS WHERE THE ISSUE IS
console.log("No Listings");
listingsExist = false;
} else {
// if listings do exist, log them to console
console.log(listing);
}
});
}
}
// Return listing data from API
async function getListing(page) {
try {
const response = await axios.get(`https://mlb19.theshownation.com/apis/listings.json?type=Stadium&page=1}`);
return response.data.listings;
} catch (error) {
console.error(error);
}
}
loopThroughListings();
答案 0 :(得分:2)
您需要先将loopThroughListings
设置为async
,然后才能await getListing()
像这样:
const axios = require('axios');
// Loop through multiple pages of listings in the API
async function loopThroughListings() {
let listingsExist = true;
// Loop through listings until they don't exist
while (listingsExist) {
const listing = await getListing();
if (listing.length < 1) {
// if listings don't exist, stop the loop
// THIS IS WHERE THE ISSUE IS
console.log("No Listings");
listingsExist = false;
} else {
// if listings do exist, log them to console
console.log(listing);
}
}
}
// Return listing data from API
async function getListing(page) {
try {
const response = await axios.get(`https://mlb19.theshownation.com/apis/listings.json?type=Stadium&page=1}`);
return response.data.listings;
} catch (error) {
console.error(error);
}
}
loopThroughListings();
就个人而言,因为while循环当然至少会运行一次,所以我改用do/while
-对我来说,这使代码的流程更加明显
do {
const listing = await getListing();
if (listing.length < 1) {
// if listings don't exist, stop the loop
// THIS IS WHERE THE ISSUE IS
console.log("No Listings");
listingsExist = false;
} else {
// if listings do exist, log them to console
console.log(listing);
}
} while(listingsExist);
但这只是一个见解