MDN self-hosted library · e01.org

Subscriber: signal property

Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.

js
const observable = new Observable((subscriber) => {
  fetch("/data.json", { signal: subscriber.signal })
    .then((response) => {
      if (!response.ok) {
        throw new Error(`Request failed: ${response.status}`);
      }
      return response.json();
    })
    .then((data) => {
      subscriber.next(data);
      subscriber.complete();
    })
    .catch((error) => {
      if (subscriber.active) {
        subscriber.error(error);
      }
    });
});

const controller = new AbortController();
observable.subscribe(
  {
    next(data) {
      console.log(data);
    },
    error(error) {
      console.error(error);
    },
  },
  { signal: controller.signal },
);

// To cancel the subscription and any pending request:
// controller.abort();