Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limiting asynchronous calls in Node.js

I've got a Node.js app that gets a list of file locally and uploads them to a server. This list could contain thousands of files.

for (var i = 0; i < files.length; i++) {    upload_file(files[i]); } 

If I execute this with thousands of files, upload_file will get called thousands of times all at once, and most likely die (or at least struggle). In the synchronous world, we'd create a thread pool and limit it to a certain number of threads. Is there a simple way to limit how many asynchronous calls get executed at once?

like image 263
Jon Nichols Avatar asked Mar 02 '12 20:03

Jon Nichols


People also ask

How do you stop asynchronous call in node JS?

When a method is running, and another method is called to stop the first method, I start an infinite loop to stop that code from running and then remove the method from the queue(array).

How do you handle multiple asynchronous calls in node JS?

In order to run multiple async/await calls in parallel, all we need to do is add the calls to an array, and then pass that array as an argument to Promise. all() . Promise. all() will wait for all the provided async calls to be resolved before it carries on(see Conclusion for caveat).

Why node js is asynchronous non-blocking?

Non-Blocking methods are executed asynchronously. Asynchronously means that the program may not necessarily execute line by line. The program calls the function and move to the next operation and does not wait for it to return.

Is NodeJS require synchronous or asynchronous?

NodeJS is an asynchronous event-driven JavaScript runtime environment designed to build scalable network applications. Asynchronous here refers to all those functions in JavaScript that are processed in the background without blocking any other request.


1 Answers

As usual, I recommend Caolan McMahon's async module.

Make your upload_file function take a callback as it's second parameter:

var async = require("async");  function upload_file(file, callback) {     // Do funky stuff with file     callback(); }  var queue = async.queue(upload_file, 10); // Run ten simultaneous uploads  queue.drain = function() {     console.log("All files are uploaded"); };  // Queue your files for upload queue.push(files);  queue.concurrency = 20; // Increase to twenty simultaneous uploads 
like image 138
Linus Thiel Avatar answered Sep 20 '22 18:09

Linus Thiel