Javascript 图像不会在第一页呈现
我试图做一个简单的应用程序,调用api,每页呈现10幅图像。 第一页加载但不显示图像,但第二页显示图像 我做错了什么Javascript 图像不会在第一页呈现,javascript,html,asynchronous,Javascript,Html,Asynchronous,我试图做一个简单的应用程序,调用api,每页呈现10幅图像。 第一页加载但不显示图像,但第二页显示图像 我做错了什么 let imageData = []; fetch({api} ).then(res => res.json()) .then((data) => { imageData.push(...data.results) }) fetch({api} ).then(res => res.json()) .then((data) => {
let imageData = [];
fetch({api}
).then(res => res.json())
.then((data) => {
imageData.push(...data.results)
})
fetch({api}
).then(res => res.json())
.then((data) => {
imageData.push(...data.results)
})
let currentPage = 1;
let imagesPerPage = 10;
const changePage = (page)=> {
let nextBttn = document.getElementById("nextBttn");
let prevBttn = document.getElementById("prevBttn");
let root = document.getElementById("root");
let pageCount = document.getElementById("page");
if (page < 1) page = 1;
if (page > numPages()) page = numPages();
root.innerHTML = "";
for (var i = (page - 1) * imagesPerPage; i < (page * imagesPerPage) && i < imageData.length; i++) {
const createImage = document.createElement('img')
createImage.src = imageData[i].urls.thumb
createImage.setAttribute('id',imageData[i].id)
root.appendChild(createImage)
}
pageCount.innerHTML = page + "/" + numPages();
window.onload = ()=>{
changePage(1);
};
让imageData=[];
获取({api}
).then(res=>res.json())
。然后((数据)=>{
imageData.push(…data.results)
})
获取({api}
).then(res=>res.json())
。然后((数据)=>{
imageData.push(…data.results)
})
设currentPage=1;
设imagesPerPage=10;
常量更改页=(页)=>{
设nextbtn=document.getElementById(“nextbtn”);
让prevBttn=document.getElementById(“prevBttn”);
让root=document.getElementById(“root”);
让pageCount=document.getElementById(“页面”);
如果(第<1页)第=1页;
如果(page>numPages())page=numPages();
root.innerHTML=“”;
对于(var i=(第1页)*imagesPerPage;i<(第*页imagesPerPage)和&i{
更改页面(1);
};
有两次抓取,因为它返回30个图像,而我需要60个图像。问题是您有两个(技术上有三个)异步任务正在运行 它们相互依赖,但没有任何代码来同步备份 以下是事件的可能顺序:
let response1 = fetch({api})
.then(res => res.json())
.then((data) => {
imageData.push(...data.results)
});
let response2 = fetch({api})
.then(res => res.json())
.then((data) => {
imageData.push(...data.results)
});
Promise.all([response1, response2])
.then(() => changePage(1));
// Remove onLoad callback because we don't really care when the page loads, we care when the data loads.