gpt4 book ai didi

javascript - 可观察对象相对于异步迭代器的优势

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:08:21 27 4
gpt4 key购买 nike

Observables 异步推送它们的数据,我感兴趣的是它们与拉取数据的对应对象(即异步可迭代对象)相比如何。

我遇到了这个 ReactiveX article

You can think of the Observable class as a “push” equivalent to Iterable, which is a “pull.” With an Iterable, the consumer pulls values from the producer and the thread blocks until those values arrive. By contrast, with an Observable the producer pushes values to the consumer whenever values are available. This approach is more flexible, because values can arrive synchronously or asynchronously.

特别是,我不明白最后引用的那一行。有人可以解释一下推送的所谓优势吗?

最佳答案

Observables push their data through asynchronously

那是不正确的。它可以是同步的和异步的


您帖子中的引用指向 [Symbol.iterator],而不是新的 ES2015 [Symbol.asyncIterator]


This approach is more flexible, because values can arrive synchronously or asynchronously

因此与[Symbol.iterator] 相比,Observable 不会阻塞线程,而且可以在同步和异步源上工作。


将 Observable 与 [Symbol.asyncIterator] 进行比较,来自 MDN 的重要引述:

There are currently no built-in JavaScript objects that have the [Symbol.asyncIterator] key set by default

所以 [Symbol.asyncIterator] 对比 Observable:

[Symbol.asyncIterator]:

const myAsyncIterable = new Object();
myAsyncIterable[Symbol.asyncIterator] = async function*() {
yield "hello";
yield "async";
yield "iteration!";
};

(async () => {
for await (const x of myAsyncIterable) {
console.log(x);
// expected output:
// "hello"
// "async"
// "iteration!"
}
})();

可观察:

of('hello', 'async', 'iteration!').subscribe(console.log)

关于javascript - 可观察对象相对于异步迭代器的优势,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56800590/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com