How to know when finished

Im pretty new to node.js, so I'm wondering how to find out when all elements are processed, say:

["one", "two", "three"].forEach(function(item){ processItem(item, function(result){ console.log(result); }); }); 

... now, if I want to do something that can only be done by processing all the elements, how would I do it?

+4
source share
3 answers

You can use the asynchronous module . A simple example:

 async.map(['one','two','three'], processItem, function(err, results){ // results[0] -> processItem('one'); // results[1] -> processItem('two'); // results[2] -> processItem('three'); }); 

The async.map callback function will execute when all items are processed. However, in the process you have to be careful, the processItem should be something like this:

 processItem(item, callback){ // database call or something: db.call(myquery, function(){ callback(); // Call when async event is complete! }); } 
+5
source

forEach is blocked, see this post:

JavaScript, Node.js: is Array.forEach asynchronous?

therefore, to call the function when all the elements are processed, it can be done inline:

 ["one", "two", "three"].forEach(function(item){ processItem(item, function(result){ console.log(result); }); }); console.log('finished'); 

if for each element being processed there is a high load with reference to the i-th, then look at the module that Mustafa recommends. There is also a template referenced by the link linked above.

+2
source

Although the other answers are correct, since node.js now supports ES6, in my opinion, using the built-in Promise library will be more stable and tidy.

You don’t even need to demand anything, Ecma took the library Promises / A + and implemented it in its own Javascript.

 Promise.all(["one", "two","three"].map(processItem)) .then(function (results) { // here we got the results in the same order of array } .catch(function (err) { // do something with error if your function throws } 

Since Javascript is a rather problematic language (dynamic typing, asynchronous stream) when it comes to debugging, using Promise instead of callbacks will save you time in the end.

0
source

Source: https://habr.com/ru/post/1414632/


All Articles