I've been trying to wrap my head around this issue for the last hours but can't figure it out. I guess I still have to get used to the functional programming style ;)
I wrote a recursive function that traverses through a directory structure and does things to certain files. This functions uses the asynchronous IO methods. Now I want to perform some action when this whole traversing is done.
How would I make sure that this action is performed after all parse
calls have been performed but still use the asynchronous IO functions?
var fs = require('fs'), path = require('path'); function parse(dir) { fs.readdir(dir, function (err, files) { if (err) { console.error(err); } else { // f = filename, p = path var each = function (f, p) { return function (err, stats) { if (err) { console.error(err); } else { if (stats.isDirectory()) { parse(p); } else if (stats.isFile()) { // do some stuff } } }; }; var i; for (i = 0; i < files.length; i++) { var f = files[i]; var p = path.join(dir, f); fs.stat(p, each(f, p)); } } }); } parse('.'); // do some stuff here when async parse completely finished
The simplest way to execute a method asynchronously is to start executing the method by calling the delegate's BeginInvoke method, do some work on the main thread, and then call the delegate's EndInvoke method. EndInvoke might block the calling thread because it does not return until the asynchronous call completes.
Synchronous means that you call a web service (or function or whatever) and wait until it returns - all other code execution and user interaction is stopped until the call returns. Asynchronous means that you do not halt all other operations while waiting for the web service call to return.
Asynchronous Writes. Synchronous API calls are blocking calls that do not return until either the change has been completed or there has been an error. For asynchronous calls, the response to the API call is returned immediately with a polling URL while the request continues to be processed.
Synchronous request — (Default) Where the client blocks and waits for the result of the remote request before continuing execution. Asynchronous request — Where the client continues execution after initiating the request and processes the result whenever the AppServer makes it available.
Look for Step module. It can chain asynchronous functions calls and pass results from one to another.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With