Loading

Promise Example

  1. // document.querySelectorAll will return a static NodeList and can use CSS selectors to filter.
  2. var anchors = document.querySelectorAll("a[href*='/transactions/']")
  3.  
  4. // NodeList can be converted to a true Array using Array.from,
  5. // which provides Array.prototype methods
  6. // Array.prototype.map will return a new array with the returned values.
  7. // fetch() returns a promise, so returning fetch(anchor) will return the promise of the fetch
  8. // into an array to be used with Promise.all()
  9. var promises = Array.from(anchors).map(anchor => fetch(anchor));
  10.  
  11. function parseResult(result) {
  12.     // Parse the result
  13. }
  14.  
  15. // Promise.all() accepts an array of promises and will resolve when all resolve.
  16. Promise.all(promises).then(function (results) {
  17.     results.forEach(parseResult);
  18. }).catch(function (reason) {
  19.     // One or more of the promises was rejected.
  20. });