@@ -3,7 +3,7 @@ package japgolly.scalajs.react
33import japgolly .scalajs .react .internal .{RateLimit , SyncPromise , Timer , catchAll , identityFn , newJsPromise }
44import java .time .Duration
55import scala .collection .compat ._
6- import scala .concurrent .duration .FiniteDuration
6+ import scala .concurrent .duration .{ FiniteDuration , MILLISECONDS }
77import scala .concurrent .{ExecutionContext , Future }
88import scala .scalajs .js
99import scala .scalajs .js .{Thenable , timers , | }
@@ -826,4 +826,30 @@ final class AsyncCallback[A] private[AsyncCallback] (val completeWith: (Try[A] =
826826 def fork_ : Callback =
827827 delayMs(1 ).toCallback
828828
829+ /** Record the duration of this callback's execution. */
830+ def withDuration [B ](f : (A , FiniteDuration ) => AsyncCallback [B ]): AsyncCallback [B ] = {
831+ val nowMS : AsyncCallback [Long ] = CallbackTo .currentTimeMillis.asAsyncCallback
832+ for {
833+ s <- nowMS
834+ a <- self
835+ e <- nowMS
836+ b <- f(a, FiniteDuration (e - s, MILLISECONDS ))
837+ } yield b
838+ }
839+
840+ /** Log the duration of this callback's execution. */
841+ def logDuration (fmt : FiniteDuration => String ): AsyncCallback [A ] =
842+ withDuration((a, d) =>
843+ Callback .log(fmt(d)).asAsyncCallback ret a)
844+
845+ /** Log the duration of this callback's execution.
846+ *
847+ * @param name Prefix to appear the log output.
848+ */
849+ def logDuration (name : String ): AsyncCallback [A ] =
850+ logDuration(d => s " $name completed in $d. " )
851+
852+ /** Log the duration of this callback's execution. */
853+ def logDuration : AsyncCallback [A ] =
854+ logDuration(" AsyncCallback" )
829855}
0 commit comments