【发布时间】:2021-10-19 03:33:20
【问题描述】:
假设我使用 async/await 的代码运行良好:
async function getMeSomething() : Promise<Something> {
// some async code
}
async function getMeStuff() : Promise<Stuff> {
// some async code
}
async function getMeSomethingWithStuff: Promise<SomethingWithStuff> {
const something: Something = await getMeSomething();
const stuff: Stuff = await getMeStuff();
return new SomethingWithStuff(something, stuff);
}
这段代码可以有效地用 Promise 编写,就像任何使用 async/await 的代码一样(只是更长):
// this is strictly equivalent to previous example, including exception management
function getMeSomethingWithStuff: Promise<SomethingWithStuff> {
let something;
return getMeSomething().then((res) => {
something = res;
return getMeStuff();
}).then((stuff) => {
return new SomethingWithStuff(something, stuff);
});
}
当调用第三个函数时,它会调用第一个和第二个,合并结果并以第三个函数的调用者不知道调用了哪些底层函数的方式返回最终结果:
const somethingWithStuff: SomethingWithStuff = getMeSomethingWithStuff();
// we have the result, we don't care how we got it, the logic is completely encapsulated
我们如何仅使用 rxjs 编写等效代码?
// the following two functions are already defined and we can't redefine them
function getMeSomething() : Observable<Something> {
// some async code
}
function getMeStuff() : Observable<Stuff> {
// some async code
}
// we want to define this function that should return an observable
function getMeSomethingWithStuff: Observable<SomethingWithStuff> {
// what's the code ?
}
规则:
- 不得使用 Promise、async/await 或可观察对象与 Promise 之间的转换作弊,只能使用 rxjs
- 必须正确处理异常
这似乎是一个微不足道的问题,但尽管仔细阅读了 rxjs 的文档和大量教程,但我自己却找不到答案。
【问题讨论】:
-
来自 RXJS 将 promise 转换为 observable。 learnrxjs.io/learn-rxjs/operators/creation/from
-
你不能,这是规则中的:D.
-
输入代码时,可以像meta.stackexchange.com/questions/184108/…那样应用语法高亮
标签: angular rxjs observable rxjs-observables