Stuck in an asynchronous loop with wrapAsync

My goal is to loop through asynchronously:

client.js :

 abc = function() { for (var i = 0; i <= 49; i++) { console.log(i); Meteor.call('testBla', i) } } 

server.js

 testBla: function(i) { function asyncCall() { console.log('inside asyncCall', i) return 'done'; } var syncCall = Meteor.wrapAsync(asyncCall); console.log('a'); var res = syncCall(i); console.log('b') return res; } 

Console:

 a inside asyncCall 0 

Why is he stuck?

+1
source share
1 answer

Functions that you can pass to Meteor.wrapAsync must have a certain signature: their arguments must end with a callback taking into account two arguments: an error and a result.

Inside the body of the async function, you must call the callback either with an error in the event of a function failure, or with the result if everything is in order.

 function asyncHelloWorld(callsCount, callback){ // simulate fake error every 5 calls if(callsCount % 5 === 0){ callback("error"); } callback(null,); } for(var i = 0; i < 50; i++){ asyncHelloWorld(i, function(error, result){ if(error){ console.log(error.reason); return; } console.log(result); }); } 

You can only wrap functions that respect this signature and behavior, which is a standard inherited from Node.JS.

When you complete the async functions, be sure to use the try / catch block if you want to handle a potential error.

 Meteor.methods({ helloWorld: function(i){ var syncHelloWorld = Meteor.wrapAsync(asyncHelloWorld); console.log("a"); try{ var res = syncHelloWorld(i); console.log("b") return res; } catch(exception){ console.log(exception); console.log("c"); // do not recover, propagates the exception back to the client (standard behavior) throw exception; } } }); 
0
source

All Articles