繁体   English   中英

setTimeout / Promise.resolve:Macrotask vs Microtask

[英]setTimeout / Promise.resolve: Macrotask vs Microtask

我已经介绍了Microtasks和Macrotasks的概念已经有一段时间了,从我读过的所有内容来看,我一直认为setTimeout被认为是创建一个Promise.resolve()Promise.resolve() (或Promise.resolve() process.nextTick )创建微任务。

(是的,我知道像Q和Bluebird这样的不同Promise库有不同的调度程序实现,但这里我指的是每个平台上的本机Promises)

考虑到这一点,我无法解释NodeJS上的以下事件序列(Chrome上的结果与NodeJS(v8 LTS和v10)不同,并且符合我对此主题的理解)。

 for (let i = 0; i < 2; i++) { setTimeout(() => { console.log("Timeout ", i); Promise.resolve().then(() => { console.log("Promise 1 ", i); }).then(() => { console.log("Promise 2 ", i); }); }) } 

因此,我在Chrome上的结果(与我对Micro / Macro任务的理解以及Promise.resolve和setTimeout的行为方式一致)是:

Timeout  0
Promise 1  0
Promise 2  0
Timeout  1
Promise 1  1
Promise 2  1

在NodeJS输出上执行的代码相同:

Timeout  0
Timeout  1
Promise 1  0
Promise 2  0
Promise 1  1
Promise 2  1

我正在寻找一种在Chrome上使用NodeJS获得相同结果的方法。 我还测试了process.nextTick而不是Promise.resolve()但结果是一样的。

有人能指出我正确的方向吗?

您无法控制不同的体系结构如何排列承诺和超时。

优秀阅读: https//jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/

如果你想要相同的结果,你将不得不链接承诺。

 let chain = Promise.resolve(null) for (let i = 0; i < 2; i++) { console.log("Chaining ", i); chain = chain.then(() => Promise.resolve() .then(() => { setTimeout(() => { console.log("Timeout ", i); Promise.resolve() .then(() => { console.log("Promise 1 ", i); }) .then(() => { console.log("Promise 2 ", i); }) }, 0) })) } chain.then(() => console.log('done')) 

这被NodeJs团队认为是一个错误,更多详情请点击这里: https//github.com/nodejs/node/issues/22257

同时它已经修复并发布了Node v11的一部分。

最好的,何塞

我不是说我做对了,我写了一些adhoc,我希望你测试下面的内容:

包装器:

function order(){
    this.tasks = [];
    this.done = false;
    this.currentIndex = 0;
    this.ignited = false;
}
order.prototype.push = function(f){
    var that =  this,
        args = Array.prototype.slice.call(arguments).slice(1);
    if(this._currentCaller){
        this.tasks.splice(
            this.tasks.indexOf(this._currentCaller) + 1 + (this.currentIndex++),
            0,
            function(){that._currentCaller = f; f.apply(this,args);}
        );
    } else {
        this.tasks.push(function(){that._currentCaller = f; f.apply(this,args);});
    }
    !this.ignited && (this.ignited = true) && this.ignite();
    return this;
}
order.prototype.ignite = function(){
    var that = this;
    setTimeout(function(){
        if(that.tasks.length){
            that.tasks[0]();
            that.tasks.shift();
            that.repeat(function(){that.reset(); that.ignite()});
        } else {
            that.ignited = false;
            that.reset();
        }
    },0);
}
order.prototype.repeat = function(f){
    var that = this;
    if(this.done || !this.tasks.length){
        f();
    } else {
        setTimeout(function(){that.repeat(f);},0);
    }
}
order.prototype.reset = function(){
    this.currentIndex = 0; 
    delete this._currentCaller; 
    this.done = false;
}

使用:

创建一个实例:

var  x = new order;

然后稍微修改其余部分:

for (let i = 0; i < 2; i++) {
    x.push(function(i){
        setTimeout(() => {
            console.log("Timeout ", i);
            x.push(function(i){
                Promise.resolve().then(() => {
                    console.log("Promise 1 ", i);
                }).then(() => {
                    console.log("Promise 2 ", i);
                    x.done = true;
                })
            },i);
            x.done = true;
        });
    },i);
}

我明白了:

Timeout  0
Promise 1  0
Promise 2  0
Timeout  1
Promise 1  1
Promise 2  1

你甚至可以详细说明一下:

for (let i = 0; i < 2; i++) {
    x.push(function(i){
        setTimeout(() => {
            console.log("Timeout ", i);
            x.push(function(i){
                Promise.resolve().then(() => {
                    console.log("Promise 1 ", i);
                }).then(() => {
                    console.log("Promise 2 ", i);
                    x.done = true;
                })
            },i)
            .push(function(i){
                Promise.resolve().then(() => {
                    console.log("Promise 1 ", i);
                }).then(() => {
                    console.log("Promise 2 ", i);
                    x.done = true;
                })
            },i+0.5)
            .push(function(i){
                Promise.resolve().then(() => {
                    console.log("Promise 1 ", i);
                }).then(() => {
                    console.log("Promise 2 ", i);
                    x.done = true;
                })
            },i+0.75);
            x.done = true;
        });
    },i);
}

在节点v6中,您将获得:

Timeout  0
Promise 1  0
Promise 2  0
Promise 1  0.5
Promise 2  0.5
Promise 1  0.75
Promise 2  0.75
Timeout  1
Promise 1  1
Promise 2  1
Promise 1  1.5
Promise 2  1.5
Promise 1  1.75
Promise 2  1.75

你会在我的节点版本中尝试这个吗? 在我的节点(6.11,我知道它的旧)它的工作原理。

测试了chrome,firefox,节点v6.11

注意:您不必保持对'x'的引用, this在推送的函数中引用了order实例。 您还可以使用Object.defineProperties来呈现Object.defineProperties配置的getter / setter,以防止意外删除instance.ignited等。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM