Stuck in async loop with wrapAsync

℡╲_俬逩灬. 提交于 2019-12-13 19:50:31

问题


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:


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;
    }
  }
});


来源:https://stackoverflow.com/questions/30442972/stuck-in-async-loop-with-wrapasync

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!