I want to make a function decorator and measure async's function execution time, and return resolve or reject results as indented without decorating. Any clue how to achieve this? Most guides are about sync functions and are not touching the async world.
This is an example to illustrate the desired functionality
async exampleFunction () {
try{
const response = await aPromise() // The goals is to measure this one with a decorator measure(aPromise) and dispatch actions if the fetching takes a long time
}
catch (err){
// Do something with error
}
Here's a higher-order function that can measure the time it takes for the returned promise to settle either by fulfilling or rejecting:
function measure(fn) {
return async (...args) => {
const begin = performance.now();
try {
return await fn(...args);
} finally {
const end = performance.now();
console.log(`Execution time: ${end - begin}`);
}
};
}
Example usage:
exampleFunction();
async function exampleFunction() {
try {
const value = await measure(defer)('foo', 1000);
// where normally you'd write:
// const value = await defer('foo', 1000);
console.log(`Resolved with ${value}`);
} catch (reason) {
console.log(`Rejected with ${reason}`);
}
}
function measure(fn) {
return async (...args) => {
const begin = performance.now();
try {
return await fn(...args);
} finally {
const end = performance.now();
console.log(`Execution time: ${end - begin}`);
}
};
}
function defer(result, ms) {
return new Promise((resolve, reject) => {
setTimeout(() => {
const settle = Math.random() < 0.5 ? resolve : reject;
settle(result);
}, ms);
});
}