Stuck in async loop with wrapAsync

2019-08-07 23:45发布

My goal is to go through a loop 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 does it stuck?

1条回答
狗以群分
2楼-- · 2019-08-08 00:29

Functions you can pass to Meteor.wrapAsync must have a specific signature : their arguments must end with a callback given 2 arguments : error and result.

Inside an async function body, you must invoke the callback with either an error in case the function fails, or the result if everything is OK.

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 wrap async functions, don't forget to use a try/catch block if you want to handle the 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;
    }
  }
});
查看更多
登录 后发表回答