Use promise instead of callback for settimeout

You should all be familiar with ES6 promises by now as a way of handling asynchronicity in a more organized way. The simplest kind of asynch that we regularily come across in JavaScript is setTimeout, which normally takes this pattern.

setTimeout (function() {
   // do something after waiting 1000 milliseconds
}, 1000);

This is just fine, until you have more that one going on and you need to do something based on all of them having completed. This is where promises come into their own. Here's setTimeout, but promise based.
/*
 * settimeout as a promise
 * @param {number} ms number of ms to wait
 * @param {*} [tag] optional tag that will be returned when resolved
 */
function loiter(ms, tag) {
  return new Promise(function(resolve, reject) {
    try {
      setTimeout(function() {
        resolve(tag);
      }, ms);
    } catch (err) {
      reject(err);
    }
  });
}

and you can use it like this.
loiter(500)
.then (function () {
  console.log('do something');
});

Doesn't seem like a great improvement over setTimeout, until you do this.
Promise.all ([
  loiter(2000)
  .then (function () {
    console.log('with something else');
   }),
  loiter(1000)
  .then (function () {
    console.log('do something together');
  })]).then(function(){
  console.log('its all over');
});

If you're not using promises yet, then you should have a look. Life becomes a lot simpler.

You want to learn Google Apps Script?

Learning Apps Script, (and transitioning from VBA) are covered comprehensively in my my book, Going Gas - from VBA to Apps script, available All formats are available now from O'Reilly,Amazon and all good bookshops. You can also read a preview on O'Reilly

If you prefer Video style learning I also have two courses available. also published by O'Reilly.
Google Apps Script for Developers and Google Apps Script for Beginners.






For more like this, see Google Apps Scripts snippets. Why not join our forumfollow the blog or follow me on twitter to ensure you get updates when they are available. 



Comments