简体   繁体   中英

Newbie Javascript question - Fetch in while loop

My main program flow should be:

  • read JSON (fetch api)
  • do some stuff with json
  • repeat

The problem is I cannot do a do - while because of the asynchronous nature of the fetch api.

Basically, the main() method below should repeat infinite

My code so far:

 let playbook = []; let slideIndex = 0; let reinitialize = true; function main() { loadJSON().then(r => initializeSlideshow()); } async function loadJSON() { let response = await fetch('playbook.json'); if (response.status === 200) { playbook = await response.json(); } playbook.sort(function (x, y) { return x.order - y.order; }); } function initializeSlideshow() { playbook.forEach((photo, i) => { //console.log(photo); let div = document.createElement("div"); div.className = "mySlides fade"; div.style.display = "none"; let img = document.createElement("img"); img.src = photo.uuid; img.style = "width:100% height:100%"; div.appendChild(img); document.querySelector(".slideshow-container").appendChild(div); }) startSlideShow(); } async function startSlideShow() { let slides = document.getElementsByClassName("mySlides"); slideIndex = 0 do { console.log(playbook[slideIndex].enabled) console.log(playbook[slideIndex].duration) if (playbook[slideIndex].enabled == 'true') { slides[slideIndex].style.display = "block"; //setTimeout(startSlideShow, playbook[slideIndex].duration); // Change image every 2 seconds await new Promise(r => setTimeout(r, playbook[slideIndex].duration)); slides[slideIndex].style.display = "none"; } slideIndex++; } while (slideIndex < slides.length) }

Async/Await can be used in such scenarios. The while(true) will create an infinite loop. Your main function will look something like below -

async function main() {
  while(true) {
    await loadJSON();
    await initializeSlideshow();
  }
}

async function initializeSlideshow() {
   // Logic to append images
    await startSlideShow();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM