Search code examples
javascriptes6-promise

How to write a JavaScript promise decorator


I have a preexisting JavaScript function that returns a promise. I call it like so

function on_success(result){
  //process result
}
foo(params).then(on_success)

I would like to write wrapper function, bar, that will call foo and and measure execution time. I want to call bar in the exact same manner:

bar(params).then(on_success)

ho do I do that?

This is what I ended up writing. It is a simplified version of @Sidney answer

function bar(params){
    var start_time=new Date().getTime()
    function print_time(x){
        var end_time=new Date().getTime()
        console.log(end_time-start_time)
        return x
    }
    return foo(params).then(print_time)
}

Solution

  • If I understand your question, you're looking for something like this:

    const myAsyncFunction = url =>
      fetch(url).then(res => res.text())
      
    const timePromise = (promiseFn, ...args) => {
      const start = Date.now()
      return promiseFn(...args)
        .then(result => {
          console.log(`Promise finished in ${(Date.now() - start) / 1000} seconds`)
          return result
        }, error => {
          console.log(`Promise errored in ${(Date.now() - start) / 1000} seconds`)
          return Promise.reject(error)
        })
    }
    
    timePromise(myAsyncFunction, 'https://example.com')