【发布时间】:2022-01-18 16:12:33
【问题描述】:
我制作了一个我正在工作的代码的简化示例。
import * as rx from "rxjs";
import * as op from "rxjs/operators";
async function main(): Promise<void> {
const blocker = new rx.ReplaySubject<0>();
const subscription = rx.timer(0, 1000)
.pipe(
op.take(3),
op.observeOn(rx.queueScheduler),
op.subscribeOn(rx.queueScheduler)
)
.subscribe({
next: x => console.log(`timer: next: [${x}]`),
error: err => console.log(`timer: error: [${err}]`),
complete: () => {
console.log("timer: complete");
blocker.next(0);
}
});
const promise = rx.lastValueFrom(blocker.asObservable()
.pipe(
op.single(),
op.observeOn(rx.queueScheduler),
op.subscribeOn(rx.queueScheduler)
));
console.log("prepared to await");
await promise;
console.log("awaited!");
subscription.unsubscribe();
}
main()
.then(
() => console.log("all right"),
reason => console.log(`rejected: [${reason}]`))
.catch(err => console.log(`error! : ${err}`))
.finally(() => console.log("done done done"));
它工作(排序)除了“等待!”时的部分!永远不会打印到控制台,以及main 函数返回的承诺之后的任何行。
实际的控制台输出是:
prepared to await
timer: next: [0]
timer: next: [1]
timer: next: [2]
timer: complete
我期望的是:
prepared to await
timer: next: [0]
timer: next: [1]
timer: next: [2]
timer: complete
awaited!
all right
问题:
- 为什么会这样?这里涉及的nodejs“魔法”(我假设是调度程序)是什么?你能推荐任何关于nodejs内部的书籍吗?
- 如何更改代码以实现预期输出?
谢谢。
【问题讨论】:
标签: node.js typescript async-await rxjs