【发布时间】:2020-01-30 12:00:46
【问题描述】:
在使用 API 和 Promise 方面,我是一个相当大的新手 - 所以我很难解决这个问题。
目标是向 API 发出 GET 请求并返回这些结果。但是,由于 API 将数据分散到多个页面,因此我将遍历 API 页面,直到返回 0 个列表。
我能够成功地将列表记录到控制台,但是,尽管将 listingsExist 设置为 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();
【问题讨论】:
-
getListing()是异步的,因此axios.get永远不会完成执行,因为您实际上有一个while(true){}循环
标签: javascript node.js promise axios