Totally, totally, not on topic, I am giving you a flavour of the sort of things I am breaking my head about. Javascript powers websites with unreliable connections, and in 99% of the cases it is not a big deal whether all images are rendered exactly on time. For a presentation software that renders on screen slide shows for a few hundred people or needs to produce a pitch deck in crisp PPTX or PDF, it is crucial that the right image is rendered correctly and appears in the right order, you are happy to wait a few extra milliseconds if you have to (since there is no risk of a million bored people clicking away from you ads).

Web browsers basically run like headless chickens, if one bit of rendering encounters a problem or delay, they will quickly jump to the next one, try again later, try something else. There are a bunch of Javascript commands to try and keep track of this asynchronous chaos. The theory of these is easy to understand. A decent practical explanation though, is impossible to find anywhere online (believe me, I tried).

So, here is a cheat sheet for myself, that maybe gets picked up by Google and can help a lot of people. I left out all the theoretical explanations, just the raw example code.

function unpredictable(order) {
  return new Promise(function (resolve) {
    var resultValue = 'Result from call ' + String(order)
    setTimeout(() => resolve(resultValue), Math.random() * 1000)
  })
}

function ASAP() { // Random numbers, as values come out as soon as they are available
for (let i = 1; i <= 10; i++) {        
  unpredictable(i).then(resultValue => console.log(resultValue))    
}}

function allComplete() { // One big array comes out only after everything is done    
  var promisesArray = []    
  for (let i = 1; i <= 10; i++) {       
    promisesArray.push(unpredictable(i))    
  }    
  var allPromises = Promise.all(promisesArray)    
  allPromises.then(resultArray => console.log(resultArray))
}

async function inSequence() { // Each value is released in the order it was requested
  for (let i = 1; i <= 10; i++) {        
    var resultValue = await unpredictable(i)        
    console.log(resultValue)
  }
}

ASAP()
allComplete()
inSequence()

For those who made it to the bottom of the page, I will be taken a few days vacation with my family and post less frequently over the next week.

Photo by Cristina Munteanu on Unsplash

SlideMagic: a platform for magical presentations. Free student plan available. LEARN MORE