JavaScript承诺解析持续时间
计算承诺期限的正确方法是什么JavaScript承诺解析持续时间,javascript,es6-promise,Javascript,Es6 Promise,计算承诺期限的正确方法是什么 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)=> {
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;
});
您所需要的一切:
constp1=()=>newpromise((resolve)=>setTimeout(()=>{resolve()},2000))
常量测试=异步()=>{
const startTm=Date.now();
常量结果=等待p1();
const runTm=Date.now()-startTm;
console.log(runTm);
}
test()代码>您需要的所有内容:
constp1=()=>newpromise((resolve)=>setTimeout(()=>{resolve()},2000))
常量测试=异步()=>{
const startTm=Date.now();
常量结果=等待p1();
const runTm=Date.now()-startTm;
console.log(runTm);
}
test()
您需要确保在所有先前的承诺都得到解决之后进行持续时间计算,这意味着在Log.debug()
语句之后计算runTm
,或者创建一个新的then()
块,如下所示:
/*模拟p1以演示技术*/
函数p1(){
返回新的承诺(r=>setTimeout(()=>r('我花了2秒来解决'),2000));
}
/*模拟参数数据*/
常量参数={};
/*记录开始时间*/
const startTm=Date.now();
p1(参数)。然后((o)=>{
控制台日志(startTm);
log(JSON.stringify(o));
返回o;
})
。然后((o)=>{
/*计算持续时间并记录它*/
const runTm=Date.now()-startTm;
log(`Duration was:${runTm}ms`);
/*通过结果“o”*/
返回o;
})
您需要确保在所有之前的承诺都得到解决之后进行持续时间计算,这意味着在Log.debug()
语句之后计算runTm
,或者创建一个新的then()
块,如下所示:
/*模拟p1以演示技术*/
函数p1(){
返回新的承诺(r=>setTimeout(()=>r('我花了2秒来解决'),2000));
}
/*模拟参数数据*/
常量参数={};
/*记录开始时间*/
const startTm=Date.now();
p1(参数)。然后((o)=>{
控制台日志(startTm);
log(JSON.stringify(o));
返回o;
})
。然后((o)=>{
/*计算持续时间并记录它*/
const runTm=Date.now()-startTm;
log(`Duration was:${runTm}ms`);
/*通过结果“o”*/
返回o;
})
让p1=新承诺(函数(解析、拒绝){
setTimeout(函数(){
决议(“通过”);
}, 3000);
});
让runTm;
const startTm=Date.now();
p1.那么(
(o) =>{
runTm=Date.now()-startTm;
console.log(runTm)
返回o;
});代码>
让p1=新承诺(函数(解析、拒绝){
setTimeout(函数(){
决议(“通过”);
}, 3000);
});
让runTm;
const startTm=Date.now();
p1.那么(
(o) =>{
runTm=Date.now()-startTm;
console.log(runTm)
返回o;
});
startTm不应该在then中不可见“startTm在then()中不可见”-您需要在then
处理程序中计算runTm
,顺便说一句。那么您的问题是什么?为了完成,这里有一个库:。看看源代码。他这样做很简单。startTm不应该在then中不可见“startTm在then()中不可见”-您需要在then
处理程序中计算runTm
,顺便说一句。那么您的问题是什么?为了完成,这里有一个库:。看看源代码。他是怎么做的很简单。请你的答案包括这与OP中的代码有什么不同。而且它也没有任何作用。(第一个)@jonaswillms我扩展了我的例子。请你的回答包括它与OP中的代码有什么不同。它也没有任何作用。(第一个)@jonaswillms我扩展了我的例子。