使用 rxjs asapscheduler 的执行顺序 [英] Order of execution with rxjs asapscheduler

查看:58
本文介绍了使用 rxjs asapscheduler 的执行顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑到我有以下代码:

let Rx = window['rxjs'];
const { of,
    queueScheduler,
    asapScheduler,
    asyncScheduler,
    animationFrameScheduler
} = Rx;
const { observeOn, tap } = Rx.operators;
console.clear();


let source$ = of(1, 2, 3, asapScheduler).pipe(
    tap((v) => {
        console.log('tap ', v);
    }),
)

source$.subscribe((v) => {
    console.log('Value ', v);
    Promise.resolve().then(() => {
        console.log('Microtask value ', v);
    });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.2.1/rxjs.umd.js"></script>

我使用 asapScheduler 运算符.

Which I use asapScheduler operator.

根据文档,

asap 将等待当前同步执行的代码结束,然后它会尝试尽快执行给定的任务.

asap will wait for the current synchronously executing code to end and then it will try to execute the given task as fast as possible.

上面代码的执行顺序是什么?它们是如何工作的?我没想到 tap3 会在最后打印

What's the execution order of the above code? How do they work? I would not have expected that the tap3 to print at the last

下面是输出,

tap  1
Value  1  
tap  2    // here why did this not print Microtask value 1 and Microtask value 2 after printing tap1 and value1?
Value  2
Microtask value  1
Microtask value  2
tap  3
Value  3
Microtask value  3

推荐答案

涉及的步骤:

  1. of 根据调度程序(本例中的下一个宏任务)发出第一个值
  2. 它将下一个值放入调度程序队列(微任务)
  3. 接下来的每个排放都重复第 1 步和第 2 步.

控件打印当前宏任务,

1.) tap1 和值1

1.) tap1 and value1

按照第二步,2.) tap2 和 value2执行并完成所有挂起的 asap 和 async 任务,如下所示,

as per the second step, 2.) tap2 and value2 are executed and complete all the pending asap and async tasks as below,

3.) 微任务值 1 和微任务值 2

3.)Microtask value 1 and Microtask value 2

按照第三步,

它再次遵循下面的第一步,

it again follows the first step as below,

4.) 点击 3 和值 3

4.) tap 3 and value 3

按照第二步,执行 tap4 和 value4 并完成所有挂起的 asap 和 async 任务,如下所示,

and as per the second step, tap4 and value4 are executed and completes all the pending asap and async tasks as below,

微任务值 3微任务值 4

Microtask value 3 Microtask value 4

深入参考这个文章

这篇关于使用 rxjs asapscheduler 的执行顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆