import { } from "@effection-contrib/timebox"
Timebox
Constrain any operation to complete within a certain time.
Very often you want to put a limit on how long an operation may run such as a
fetch()
of an external resource, or handling a web request. To do this, you
can use the timebox()
function. It will encapsulate the operation and either
return its result, or a otherwise a "timeout" object indicating that it did not
complete in the required time.
import { timebox } from "@effection-contrib/timebox";
import { handleRequest } from "./handle-request";
// a theoretical request handler
export function* handler(request) {
// do not let the handler run for more than 10 seconds
let result = yield* timebox(10000, () => handleRequest(request));
if (result.timeout) {
return new Response(504, "Gateway Timeout");
} else {
return result.value;
}
}
API Reference
A value successfully computed within the timeout window. It has metadata about how long it took.
Type Parameters
T
Properties
- timeoutreadonly: false
false: indicates that there was no timeout and that value was successfully computed
- valuereadonly: T
The actual value
- startreadonly: DOMHighResTimeStamp
The time that the operation began;
- endreadonly: DOMHighResTimeStamp
The time that the operation succesfully returned value
A value that did not compute within the alloted window.
Properties
- timeoutreadonly: true
true: indicates that this is a timed out result and no value is available
- startreadonly: DOMHighResTimeStamp
The time that the operation began;
- endreadonly: DOMHighResTimeStamp
The time that the operation succesfully returned value
Constrain operation
to complete within limitMS
milliseconds
Examples
Example 1
import { timebox } from "@effection-contrib/timebox";
import { handleRequest } from "./handle-request";
// a theoretical request handler
export function* handler(request: Request): Operation<Response> {
// do not let the handler run for more than 10 seconds
let result = yield* timebox(10000, () => handleRequest(request));
if (result.timeout) {
return new Response(504, "Gateway Timeout");
} else {
return result.value;
}
}
Type Parameters
T
Parameters
limitMS: number
- the maximum allowable time for
operation
to complete
operation: () => Operation<T>
- the operation to attempt
Return Type
either a completed value or a timeout