JavaScript 承诺解决持续时间

JavaScript promise resolve duration

计算承诺持续时间的正确方法是什么?

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

startTm 在 then() 中是不可见的。

更新:

我的错。 startTm 可见。那还有没有别的方法呢?

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

所有你需要的:

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();

在 const 'result' 中,你得到的结果承诺与在 'then' 回调中得到的一样。

没有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;
});

您需要确保持续时间计算发生在所有先前的承诺都已解决之后,在您的情况下,这意味着在您的 Log.debug() 语句之后计算 runTm,或者创建一个新的 then() 像这样阻止:

/* 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;
})

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