假设我们有一个像这样的简单伪代码片段:
if (myCondition){
// Async branch
myObservable
.somethingAsync()
.subscribe(x => {
doSomething(x);
});
} else {
// Sync branch
somethingSync();
}
continueBothHere();
因此,一个异步分支和一个同步分支,其中 continueBothHere() 总是在 if 语句之后执行。 假设 continueBothHere() 不需要来自任一分支的任何输入。
如何使用 Observables 实现这一点?
我想我想在 if 语句之前定义一个 Observable,这样我就可以在 if 语句之后使用它来加入分支?但这可以与真实分支中的可观察值结合起来吗?如果有的话,对于 false 分支内的 Observable 我该怎么说?也许这可以在不使用 if 语句的情况下实现?
需要明确的是:在 true 分支中,我希望执行 doSomething(x) 之后执行 continueBothHere()
最佳答案
当我处理 observable
时,我想将其包含到异步链或同步和异步操作中,这些操作应该具有相同的后续步骤,我通常从 new Promise
开始>。通过这种方式,您可以轻松地使代码异步并处理 then
block 内的数据:
new Promise (resolve => {
if (myCondition){
// Async branch
myObservable
.somethingAsync()
.take(1)
.subscribe(x => {
resolve(doSomething(x));
});
} else {
// Sync branch
resolve(somethingSync());
}
})
.then(data => {
// "data" will contain the result of "doSomething(x)" or "somethingSync()" execution, depending on "if" statement
continueBothHere();
})
关于javascript - 使用 Angular Observable 满足异步分支和同步分支,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48724748/