简体   繁体   中英

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)
}

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') 

You can handle a fulfilled promise, in your case to stop the measurement, and then pass on the return value of then , which will be a promise in itself:

function measure (measuredFunction) {
    startMeasurement()

    return measuredFunction()
        .then(stopMeasurement)
}

measure(() => foo(params)).then(on_success)

The most basic, least fancy way you could do it...

 var timer = new Date().getTime(); function foo(){ return new Promise(done=>{ setTimeout(done, 1000); }) } function on_success(result){ //process result alert("it took "+(new Date().getTime() - timer)+"ms to do that...") } let params = {} foo(params).then(on_success) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM