[英]How does flatMap execute code synchronously?
I am using flatMap
right now because it can process asynchronous code synchronously (as in one-by-one with values from previous result), but I do not know how it is doing this. 我现在正在使用flatMap
因为它可以同步处理异步代码(如与先前结果中的值一一对应),但是我不知道它是如何做到的。 The documentation doesn't seem to explain that this behavior is part of the operator. 该文档似乎并未解释此行为是操作员的一部分。
On the RxJS doc flatMap
is defined as: 在RxJS文档上, flatMap
定义为:
Projects each source value to an Observable which is merged in the output Observable. 将每个源值投影到一个Observable,将其合并到输出Observable中。
I need to process a combination of observable
, promise
, and synchronous
code within my pipe. 我需要在管道中处理observable
, promise
和synchronous
代码的组合。 Most of the time piped data depends on its predecessor: 大部分时间通过管道传输的数据取决于其前身:
from(
// asyncrhonously fetch data from server
fetchDataAsync(credentials) // returns an Observable
).pipe(
flatMap((data) => {
// process the data with a promise
return from(processDataAsync(data))
}),
flatMap((data) => {
// sanitize the data with synchronous fn
return of(sanitizeDataSync(data))
}),
flatMap((data) => {
// store the data in local storage with a promise
return from(storeDataAsync(data))
})
)
flatMap
works, but I don't know how or why. flatMap
有效,但是我不知道如何或为什么。 How I can find this behavior in other operators? 如何在其他运算符中找到这种行为?
Basically I want the benefit of observable streams that runs like your typical async function. 基本上,我希望可以像典型的异步函数一样运行的可观察流的好处。 What is the RX-way
of doing this? RX-way
做的RX-way
是什么?
async function fn() {
// asyncrhonously fetch data from server
const fetched = await fetchDataAsync(credentials).toPromise()
// process the data with a promise
const processed = await processDataAsync(fetched)
// sanitize the data with synchronous fn
const santized = sanitizeDataSync(processed)
// store the data in local storage with a promise
return await storeDataAsync(santized)
}
The flatMap
operator does not execute code sychronously: every time it receives an event of type Observable
, it subscribes to it and emits its events in the same returning Observable
. flatMap
运算符不会同步执行代码:每次接收到类型为Observable
的事件时,它都会订阅它并在返回的相同Observable
发出其事件。 By the way it's been renamed to mergeMap
in the most recent versions, which describes its behavior better. 顺便说一下,它在最新版本中已重命名为mergeMap
,从而更好地描述了其行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.