Promise Example

by badfreja

HTML

<ul id=myList>
  <li>item 1</li>
  <li>item 2</li>
  <li>item 3</li>
</ul>
<span id=myResult></span>

JavaScript

'use strict';

// This function will be called to do async things.
// But we only simulate asynchronity with setTimeout()
function doAsyncStuff(ele) {
  console.log('Called: doAsyncStuff with ' + ele.text());
  
  // The following line of code will create a new Promise
  // It will have a "then()" method which takes two callbacks as arguments for resolving (everything was OK)
  // and for rejecting (some error occured, parallel to throw in a synchronous piece of code).
  // The callbacks will only be called when the promise has been either resolved or rejected by using one of the arguments of the arrow function I pass to the constructor.
  var p = new Promise((resolve, reject) => {
    console.log('New Promise: doAsyncStuff with ' + ele.text());
    
    // Let's assume you call some async function in here.
  	// Maybe you upload your data to your server and you want to wait for the upload to finish
  	// so you can tick all the items in the list...
    // Either way, let's say the upload was a success so you can resolve the promise
    setTimeout(resolve.bind(null, ele.text()), 1000);
  });
  
  return p;
}

// This array will hold all of our promises
var proms = [];

// Traverse the list
// This call is synchronous, hence blocking
$('#myList li').each(function (index) {
  proms.push(doAsyncStuff($(this)));
});

// Promises are "then-ables". They call either the first callback on resolve or the second one on reject in the then-method.
Promise.race(proms).then(results => {
  console.log('All promises resolved!');
  $('#myResult').text('RESULT: ' + JSON.stringify(results));
}, error => {
  console.log('One or more promises rejected!');
  $('#myResult').text('ERROR: ' + error);
});

console.log('Finished');