Skip to main content
Module

x/effection/mod.ts>resource

Structured concurrency and effects for JavaScript
Latest
function resource
Re-export
import { resource } from "https://deno.land/x/effection@3.0.3/mod.ts";

Define an Effection resource

Resources are a type of operation that passes a value back to its caller while still allowing that operation to run in the background. It does this by invoking the special provide() operation. The caller pauses until the resource operation invokes provide() at which point the caller resumes with passed value.

provide() suspends the resource operation until the caller passes out of scope.

Examples

Example 1

function useWebSocket(url) {
  return resource(function*(provide) {
    let socket = new WebSocket(url);
    yield* once(socket, 'open');

    try {
      yield* provide(socket);
    } finally {
      socket.close();
      yield* once(socket, 'close');
    }
  })
}

await main(function*() {
  let socket = yield* useWebSocket("wss://example.com");
  socket.send("hello world");
});

Parameters

operation: (provide: Provide<T>) => Operation<void>

the operation defining the lifecycle of the resource

Returns

an operation yielding the resource