How to Call an Asynchronous Function N Times

  node.js, question

Now I have a vote function for online voting, and its usage is probably as follows:

jsvote(url, function(body){
 console.log(body);
 })

Now I want to vote 10 times for the same url, so I want to write like this:

jsfor (var i=0;   i < 10;  I plus)
 vote(url, function(body){
 console.log(body);
 });
 bracket

However, it failed because it was executed asynchronously. I will know by outputting the I.

jsfor (var i=0;   i < 10;  I plus)
 vote(url, function(body){
 console.log(i);
 console.log(body);
 });
 bracket

So how can I call this function correctly 10 times? I tried many searches, such asnode call a asynchronous function n timesI still haven’t found the desired result, and I can’t use forEach or something like that.


Add: This has been carried out 10 times. It seems that the problem is not here. It should be that voting requests are too frequent and restricted. I will investigate again. Thank you.

JavaScript users should study hard.

First of all, you have not explicitly asked whether to vote one after another or to vote concurrently. If you vote concurrently, your code should work normally. I don’t knowWhy do you think it failed. Your code should output body 10 times and also 10 times.iThe value of-they will probably all be10. If you want to export0 1 2 3 4 5 6 7 8 9, please search for “JavaScript closure” on this site (since this site’s search function is relatively weak, you’d better use Google search and use “site:segmentfault.com” to limit it).

Secondly, if you want to vote one by one, you need a little skill (passing the number of times through parameters). If you have studied functional programming, it should be easy to think of. Since you didn’t explicitly request it, I won’t have time to write sample code.

Finally, when asking questions, it is suggested to use as many examples as possible that others can run and reproduce the problem, which is more labor-saving for both parties.