Callback javascript function parallel

2019-08-26 01:35发布

I'm using this function to do a callback, the task is to not modify the 'f' function. The idea is to start all functions(parallel) and then end all functions and display 'Done' at the end.(runing in node).

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(final)
  };
};

This is how the output is supposed to look.

f's activity starts.

f's activity starts.

f's activity starts.

f's activity ends.

f's activity ends.

f's activity ends.

Done.

Sometimes I got that output but not always, most of the time looks like this

f's activity starts.

f's activity starts.

f's activity starts.

f's activity ends.

f's activity ends.

Done.

f's activity ends.

and I have no idea why :/

Any ideas why..

Thank you !

2条回答
Lonely孤独者°
2楼-- · 2019-08-26 01:52

The calls to onActivityDone will not necessarily happen in the same order as the calls to f. This is true regardless of the block structure you have used, which I have never seen done before and only seems to confuse the situation.

setTimeout returns immediately - it is not like a "sleep" function that blocks execution until a certain amount of time has passed, it simply stores the callback and the time to wait and then carries on, and Javascript keeps an internal timer to call the callback when the time comes.

查看更多
【Aperson】
3楼-- · 2019-08-26 01:53

I guess your last part should look like this:

f( function() {
  f( function() {
    f(final)
  });
});

And the output will be predicted:

f's activity starts. (index):22
f's activity ends. (index):26
f's activity starts. (index):22
f's activity ends. (index):26
f's activity starts. (index):22
f's activity ends. (index):26
Done 

The following code you provided is not even compilable:

f() {
  f() {
    f(final)
  };
};

Maybe you wanted something like this:

f ( f ( f(final)));

But it is incorrect too, because code will be executed in the wrong direction. f(final) will be executed first!

EDIT

If you need to start 3 tasks in parallel use https://github.com/caolan/async#parallel

查看更多
登录 后发表回答