大网数据广告活动
Web 标准与前端开发

Observable: from() static method

· 52CE 我爱测

The **`from()`** static method of the Observable interface returns an observable converted from a promise, iterable, or async iterable; existing observables are returned unchanged.

Observable API

The from() static method of the Observable interface returns an observable converted from a promise, iterable, or async iterable; existing observables are returned unchanged.

Syntax

Observable.from(value)

Parameters

Return value

An Observable. If value is already an observable, it is returned unchanged. Otherwise, a new observable is returned that emits values from value when subscribed to.

Exceptions

  • TypeError
    • : Thrown if value cannot be converted to an observable. Primitive values, including strings, are not accepted.

Description

The conversion checks for an existing observable first, then an async iterable, then an iterable, and finally a promise.

  • A promise contributes its fulfillment value, followed by completion. A rejection becomes an error.
  • An iterable contributes its values synchronously, followed by completion when the iterator is exhausted.
  • An async iterable contributes its values as they become available, followed by completion when the iterator is exhausted.

Errors while iterating become errors in the observable.

Calling from() does not subscribe to the returned observable. However, converting an existing promise does not defer the work that created it. Unsubscribing also does not cancel that work. If the promise rejects after the subscriber becomes inactive, the error is reported to the global object.

Many methods that take observables, such as Observable.takeUntil(), implicitly convert the argument to observables, so you can pass promises, iterables, and async iterables as well.

Examples

Converting a synchronous iterable

Calling from() creates the observable without starting iteration. In this example, subscribing delivers all array values and the completion notification before subscribe() returns:

const observable = Observable.from([1, 2, 3]);

console.log("Before subscribing");
observable.subscribe({
  next(value) {
    console.log(value);
  },
  complete() {
    console.log("Complete");
  },
});
console.log("After subscribing");

// Before subscribing
// 1
// 2
// 4
// Complete
// After subscribing

Converting a promise

This example converts a promise for the first button click into an observable. It displays the click's coordinates, then a completion message. Click Restart after the stream ends to try again.

<button>Click me</button>
<p>Waiting for a click</p>
<button id="restart" disabled>Restart</button>
const btn = document.querySelector("button");
const output = document.querySelector("p");
const restart = document.querySelector("#restart");

function start() {
  restart.disabled = true;
  output.textContent = "Waiting for a click";
  const firstClick = btn.when("click").first();

  Observable.from(firstClick).subscribe({
    next(event) {
      output.textContent = `${event.clientX},${event.clientY}`;
    },
    complete() {
      restart.disabled = false;
      output.textContent += " — Complete.";
    },
  });
}

restart.when("click").subscribe(start);
start();

from-promise

Converting an async iterable

This example logs chunks of text from a fetched file. The decoded ReadableStream is an async iterable; each chunk may contain part of a line or several lines.

const response = await fetch("/data.txt");
if (!response.ok) {
  throw new Error(`Request failed: ${response.status}`);
}

const textStream = response.body.pipeThrough(new TextDecoderStream());

Observable.from(textStream).subscribe({
  next(chunk) {
    console.log(chunk);
  },
  error(error) {
    console.error("Reading failed:", error);
  },
  complete() {
    console.log("Stream complete");
  },
});

Specifications

Browser compatibility

See also

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。