1 回答
TA贡献1863条经验 获得超2个赞
对不起。我今天很累,忘记了代码的异步特性。
这是完全有效的示例(即使没有 apiKey)。你可以运行它:
//const originalUrl = `https://api.hypixel.net/skyblock/auctions?key=${apikey}`;
const originalUrl = `https://api.hypixel.net/skyblock/auctions?rnd=1`;
const nameToSearch = 'Enchanted Book';
function showLoaded(count, total) {
const el = document.getElementById('loader');
if (count) el.innerText = '' + count + ' of ' + total;
else el.innerText = 'ALL';
}
function fetchAPI(string) {
return fetch(string)
.then(response => response.json());
}
function getAuctionsFromPage(page, totalPages) {
return fetchAPI(originalUrl + `&page=${page}`)
.then(result => {
loaded++;
showLoaded(loaded, totalPages);
return result.auctions
})
.then(auctions => auctions.filter(auction => auction.item_name == nameToSearch));
}
let loaded = 0;
function collectData(totalPages) {
const allPages = [];
loaded = 0;
for (let i = 0; i < totalPages; i++) {
allPages.push(getAuctionsFromPage(i, totalPages));
}
return Promise.all(allPages)
.then(auctions => auctions.flat(1))
.then(auctions => {
showLoaded();
return {
auctions
}
});
}
function saveToFile(data) {
// Put data to file
fs.appendFile('finalresult.json', JSON.stringify(data), err => {
if (err) console.log(err);
});
}
function saveToConsole(data) {
const jsonData = JSON.stringify(data);
//console.log(jsonData);
document.getElementById('console').innerHTML = 'We found ' + data.auctions.length + ' items named ' + nameToSearch + '<br/>Data size is ' + jsonData.length + ' bytes';
}
try {
document.getElementById('loader').innerText = 'Getting total pages...';
fetchAPI(originalUrl)
.then(result => result.totalPages)
.then(totalPages => collectData(totalPages))
.then(data => saveToConsole(data));
} catch (error) {
console.log(error);
}
<div>Loaded: <span id="loader">0</span></div>
<div id="console"></div>
注意:要将数据保存到文件中,您需要更改.then(data => saveToConsole(data))
为.then(data => saveToFile(data))
添加回答
举报