Home Blog CV Projects Patterns Notes Book Colophon Search

ES6 time a promise

7 Jan, 2017

function makeTimer (logError, timeProperty = 'time', errorProperty = 'error') {
  return {
    time: function (promise) {
      const start = new Date()
      return promise.then((result) => {
        result[timeProperty] = (new Date()) - start
        return result
      }).catch((error) => {
        logError(error)
        let result = {}
        result[timeProperty] = (new Date()) - start
        result[errorProperty] = error.message
        return result
      })
    }
  }
}

This timer will add a time property to the object the promise resolves to (so it makes sense for that thing to be an object).

Create a timer like this, specifying a logger and the name of the property you want to add if you like:

const timer = makeTimer(console.log, 'time')

Use it like this for a success case:

timer.time(Promise.resolve({result: 'Result'})).then((timed) => {
  console.log(timed);
});

Gives:

{ result: 'Result', time: 0 }

Since the promise was already resolved, this was very quick!

The timer also works with promises that get rejected. It will create an object with an error key for the actual error, and a time key for the time. For example:

timer.time(Promise.reject(new Error('An error!'))).then((timed) => {
  console.log(timed);
});

Gives:

{ time: 7, error: 'An error!' }

You can copy and paste the makeTimer() function and tweak for the behaviour you'd like.

Copyright James Gardner 1996-2020 All Rights Reserved. Admin.