I'm new to node.js and I'm wondering if it is possible to iterate in a loop synchronously. Let's say that in a for loop I call a blocking function (reading, writing) and I want that the for executes synchronously (wait for first iteration to finish, then do the second one, ...)? I saw some tutorials about async module but no one covered this problem.
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fs
- Keeping track of variable instances
You shouldn't use a for loop for this. The
for
loop will fire off each of the async functions simultaneously which is obviously not what you want. You should create your own system for calling these. Try something like this:Should look a little like this:
Yours may not work exactly how I described it here, but it should use a similar concept to it.
Note: You will probably need an extra function scope to protect your original array of URL's because
.shift()
will mutate the original arrayYou mention that you are reading and writing files, are you using fs.readFile and fs.writeFile? These are asynchronous methods, and you would need to invoke one after the other in callbacks.
If you do want to use a loop, take a look at the synchronous versions of those methods fs.readFileSync and fs.writeFileSync.