【问题标题】:queue.js not asynchronously?queue.js 不是异步的?
【发布时间】:2014-03-24 06:49:34
【问题描述】:

我想并行运行多个任务并使用 mbostock 的 queue.js。我使用 Sleep() 运行以下代码,因此希望其他较轻的任务在繁重的任务之前完成 任务,而所有任务同时执行。但是下面的代码导致任务顺序执行

2 1 test.html:128
1000 2 test.html:134
4 3 test.html:128
3000 4 test.html:134
6 5 test.html:128

虽然我期待类似的事情(同时执行每个任务,但较轻的任务更早完成):

2 1 test.html:128 
4 3 test.html:128
6 5 test.html:128    
1000 2 test.html:134
3000 4 test.html:134

我做错了什么? 代码:

function Sleep(ms) {
    var d1 = new Date().getTime();
    var d2 = new Date().getTime();
    while( d2 < (d1 + ms) ) {
        d2 = new Date().getTime();
    }
    return;
}

var tmp_list = [];
var normal = function(src){
    tmp_list.push(src);
    console.log(src,tmp_list.length);
}

var sleepy = function(src){
    Sleep(5000);
    tmp_list.push(src);
    console.log(src,tmp_list.length)
};

queue().defer(normal,2)
        .defer(sleepy,1000)
        .defer(normal,4)
        .defer(sleepy,3000)
        .defer(normal,6)
        .awaitAll(function(){});

【问题讨论】:

  • 你想在浏览器中还是在节点环境中进行?在 Javascript 中,everything 在浏览器中同步运行除了 输入/输出。
  • 我想在浏览器或客户端运行它。我不知道输入/输出在 Javascript 中不能同步运行。你能提一些很好的参考来理解这些结构或哲学吗Javascript?
  • 这个 SO 问题应该澄清一点:stackoverflow.com/questions/2035645/…

标签: javascript d3.js queue


【解决方案1】:

Javascript 的并发模型与其他语言有点不同。

在 Javascript 中,一切 同步运行除了 输入/输出。这种输入/输出通常采用 AJAX 调用的形式。您还可以使用setTimeout 函数显式让出控制。

在您的情况下,您在 Sleep 函数中创建了一个繁忙的循环:

function Sleep(ms) {
    var d1 = new Date().getTime();
    var d2 = new Date().getTime();
    while( d2 < (d1 + ms) ) {
        d2 = new Date().getTime();
    }
    return;
}

这将使 CPU 一直忙于工作,并且在完成之前不会让出控制权。但是,如果你真的想等待任务结束,你必须使用queue库为被调用函数提供的callback,并使用setTimeout

 /* cb :: function (err, result) is added by queue library to the arg list */
function sleepy = function (src, cb) {
    setTimeout(function () {
        tmp_list.push(src);
        console.log(src, tmp_list.length);
        cb(); // no errors
    }, 5000);
}

另外,我怀疑.awaitAll 之后的函数也没有被调用(因为你没有使用队列的回调)。尝试在其中输入console.log 以验证这一点。

【讨论】:

  • 哇,它修复了。非常有趣。谢谢!我不需要使用回调,因为我只想将结果添加到全局变量。
猜你喜欢
  • 2012-12-10
  • 1970-01-01
  • 2019-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-16
相关资源
最近更新 更多