1

i was learning async library and just tried some codes myself and i am issueing a problem that can`t handle, can you please look at the code down below:)

 async.parallel([ function (cb) { setTimeout(() => { let a = "asd"; console.log("AAA"); cb(a, null); }, 2000); }, function (cb) { setTimeout( () => { let b = "dasd"; console.log("BBBBB"); cb(b, null); }, 5000); } ], function (error, results) { console.log("CCC"); console.log("Errors: " + error); console.log("Results: " + results); }); 

I supposed that BBB should NOT output to the screen, but to my surprise it DOES, can you help me understand why?

5
  • Why do you think BBBBB would not be output? Commented Nov 21, 2018 at 18:35
  • because, the doc says that If any of the functions pass an error to its callback, the main callback is immediately called with the value of the error. Commented Nov 21, 2018 at 18:40
  • Ok, I see. That's true, but the setTimeout still gets called after 5 seconds regardless. Commented Nov 21, 2018 at 18:47
  • exactly, why????????????? Commented Nov 21, 2018 at 18:56
  • just, i wanted to check if the new users email and username are not taken by someone else in async.parallel but doesnt work Commented Nov 21, 2018 at 18:57

1 Answer 1

2

You are using async.parallel(). All asynchronous tasks will be executed without waiting for each other and the execution order is not guaranteed.

Here's a breakdown on how your script is executed:

  1. Both setTimeout() are set.
  2. 2000 milliseconds later, console.log("AAA") and cb(a, null) are called.
  3. cb(a, null) has an error. So the main callback is called, and async.parallel() ends.
  4. But the story does not end here. The second setTimeout() is already set. Calling the main callback will not clear the timeout.
  5. console.log("BBBBB") and cb(b, null) are called. This is why you see the output BBBBB.
  6. Because the main callback is already called, calling cb(b, null) will not do anything.
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.