Solution: Measure Execution Time for an Async Task
Explore how to use the decorator pattern to measure execution time for asynchronous tasks in Node.js. Learn to wrap async functions to log durations transparently, preserving original functionality without modifying core logic.
We'll cover the following...
We'll cover the following...
Solution explanation
Lines 2–6: We define
fetchUser, a mock async service that resolves after 100 ms. It simulates an I/O call such as fetching from a database or API.Lines 9–17: We build
withTiming(fn), a decorator that:Captures the start time with
Date.now()before calling the original function. ...