我有一个预先存在的JavaScript函数,它返回一个promise。我称之为
function on_success(result){
//process result
}
foo(params).then(on_success)
我想编写包装函数bar,它将调用foo并测量执行时间。我想以完全相同的方式打电话给吧:
bar(params).then(on_success)
我这样做吗?
这是我写完的内容。它是@Sidney答案的简化版本
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)
}
答案 0 :(得分:1)
如果我理解你的问题,你正在寻找这样的事情:
LatLngBounds bounds1 = new LatLngBounds(new LatLng(8.2,48.2), new LatLng(8.1,47.2));
LatLngBounds bounds2 = new LatLngBounds(new LatLng(8.1,48.1), new LatLng(8.0,47.1));
LatLngBounds.Builder boundsBuilder = new LatLngBounds.Builder();
boundsBuilder.include(bounds1.northeast);
boundsBuilder.include(bounds1.southwest);
boundsBuilder.include(bounds2.northeast);
boundsBuilder.include(bounds2.southwest);
LatLngBounds unionBounds = boundsBuilder.build();
答案 1 :(得分:0)
你可以处理一个履行的承诺,在你的情况下停止测量,然后传递then
的返回值,这本身就是一个承诺:
function measure (measuredFunction) {
startMeasurement()
return measuredFunction()
.then(stopMeasurement)
}
measure(() => foo(params)).then(on_success)
答案 2 :(得分:0)
你可以做到最基本,最不花哨的方式......
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)