1

what is the correct way to calculate the duration of a promise?

const startTm = Date.now();
p1(params).then(
    (o)=> {
        Log.debug(startTm);
        Log.debug(JSON.stringify(o));
        return o;
    });
const runTm = Date.now() - startTm;

The startTm is invisible inside then().

UPDATE:

my bad. startTm is visible. So is there any other ways?

 const startTm = Date.now();

 p1(params).then((o)=> {
    output = o
    console.log(startTm);
    Log.debug(JSON.stringify(o));
    let runTm = Date.now() - startTm;
    Log.debug('duration: ' + runTm + 'ms');
    return o;
});
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
Shawn
  • 5,130
  • 13
  • 66
  • 109

3 Answers3

3

All what you need:

const p1 = () => new Promise((resolve) => setTimeout(() => { resolve() }, 2000))

const test = async () => {
  const startTm = Date.now();
  const result = await p1();
  const runTm = Date.now() - startTm;
  console.log(runTm);
}

test();

In const 'result' you get result promise as you get it in 'then' callback.

Without async/awaut:

const startTm = Date.now();
p1(params).then((result)=> {
  Log.debug(startTm);
  Log.debug(JSON.stringify(result));
  const runTm = Date.now() - startTm; // only available here
  return o;
});
Timofey Goncharov
  • 1,023
  • 1
  • 6
  • 14
3

You need to ensure that the duration calculation happens after all prior promises are resolved, which in your case would mean calculating runTm after your Log.debug() statements, or creating a new then() block like so:

/* Mocking p1 to demonstrate technique */
function p1() {
  return new Promise(r => setTimeout(() => r('I took 2 seconds to resolve'), 2000));
}
/* Mock params data */
const params = {};

/* Record start time */
const startTm = Date.now();

p1(params).then((o) => {
    console.log(startTm);
    console.log(JSON.stringify(o));
    return o;
})
.then((o) => {

    /* Calculate duration and log it */
    const runTm = Date.now() - startTm;
    console.log(`Duration was: ${runTm}ms`);

    /* Pass result "o" through */
    return o;
})
Dacre Denny
  • 29,664
  • 5
  • 45
  • 65
0

let p1 = new Promise(function(resolve, reject){
  setTimeout(function(){    
    resolve('pass');
  }, 3000);
});

let runTm;
const startTm = Date.now();

p1.then(
    (o)=> {          
        runTm = Date.now() - startTm;
        console.log(runTm)
        return o;
});
Vishnu
  • 897
  • 6
  • 13