簡體   English   中英

並行函數javascript,node.js

[英]parallel function javascript, node.js

關於如何解決此“ f”功能的任何想法(paralell),輸出nedd看起來

f的活動開始。

f的活動開始。

f的活動開始。

f的活動結束。

f的活動結束。

f的活動結束。

做完了

有時,但並非總是如此,有關如何修復的任何想法(任務是不修改'f'函數)。

謝謝。

function f(cb) {
  console.log("f's activity starts.");
  var t = Math.random() * 500; //gives a num between 0 and 1000

  function onActivityDone() {
    console.log("f's activity ends.");
    if (cb) cb();
  }
  setTimeout(onActivityDone, t);

}

function final() {
  console.log('Done');
}

function first() {
  final();
}



f()
{     
f()
{
    f(first)
  };
};

這看起來有點奇怪

f()
{     
f()
{
    f(first)
  };
};

看來您正在嘗試做這樣的事情

f(function() {
  f(function() {
    f(first);
  });
});

maček給了您解決問題的答案。

您的代碼所做的等同於:

f();
f();
f(first);

花括號只是打開不必要的代碼塊。

編輯:閱讀您的評論后,我想您可能想做這樣的事情

function trace (msg)
{
    var d = new Date();
    var h = d.getHours();
    var m = d.getMinutes();
    var s = d.getSeconds();
    console.log (h + ":" + m + ":" + s + " " + msg);
}

var Synchro = new function () {
    this.num_funs = 0;
    this.funs = {};

    this.register = function(fun)
    {
        this.funs[this.num_funs] = fun;
        trace ("activity "+this.num_funs+" registered.");
        this.num_funs++;
    };

    this.start = function()
    {
        console.log("launching "+this.num_funs
            +" activit"+(this.num_funs == 1 ? 'y' : 'es'));

        this.num_active = this.num_funs;
        for (var i in this.funs)
        {
            var t = 2000 + Math.random() * 8000; // delay from 2 to 6 seconds
            setTimeout(onActivityDone, t);
        }

        var _this = this;
        function onActivityDone()
        {
            if (--_this.num_active == 0)
            {
                trace ("all functions complete")
                for (var i in _this.funs) _this.funs[i]();

            }
            else trace ("still "+_this.num_active+" to go");
        }
    };
} ();

function fun1() { trace (' hi from fun1'); }
function fun2() { trace (' hi from fun2'); }
function fun3() { trace (' hi from fun3'); }

Synchro.register (fun1);
Synchro.register (fun2);
Synchro.register (fun3);
Synchro.start();

根據評論,我編輯了答案:

function f(cb) {
    console.log("f's activity starts.");
    var t = Math.random() * 500; //gives a num between 0 and 1000

    function onActivityDone() {
        console.log("f's activity ends.");
        if (cb) cb();
    }
    setTimeout(onActivityDone, t);
}

function final() {
    console.log('Done');
}

var iterations = 1000,
    ended = 0,
    i;

function first() {
    ended++;
    if(ended == iterations) {
        final();
    }
}

for(i = 0; i < iterations; i++) { f(first) }

這個想法是僅在觸發第1000個回調時才運行final函數。 根據MDN docs,還將setTimeout0時間始終等待到父線程結束為止:

重要的是要注意,在調用setTimeout()的線程終止之前,函數或代碼段無法執行。

因此,這就是為什么所有“開始”都在“結束”之前的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM