Wednesday 24 May 2017

Async best practices

I'm somewhat new to the world of async JS/node, and am having a hard time finding the best approach(es) to the whole "everything must be async" paradigm.Let's say you want to test sending a file. You get the file size that you're sending/have sent, and then compare it to the resulting file size after the far end finished downloading it. Short of setting /*jslint node: true, stupid: true */ how to ensure the steps are synchronous, but within the asynchronous mindset?I suppose a more concise question might be that according to this I should get the file size with something like:fs.stat(`test.txt`, function(err, data){ console.log(`file size: ` + data.size); }) Which isn't useful if you want that information later. And the best way around that, which I've found, is to do:var fileSize; fs.stat(`test.txt`, function(err, data){ fileSize = data.size; }) Is that the correct/best way? Does it even actually result in a synchronous call, or would it be possible that I somehow get the remote file size prior to the local one, and fail the comparison due to some IO issue? Is there a better/cleaner way to accomplish this? Also, I would personally prefer var fileSize = fs.stat(...) direct assignments instead of 2-stepping everything, is there a way to do that in asynch syntax (that's lint compliant)?

Submitted May 24, 2017 at 06:42PM by Gr1pp717

No comments:

Post a Comment