用wrapAsync陷入异步循环

用wrapAsync陷入异步循环

本文介绍了用wrapAsync陷入异步循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是异步循环:

client.js:

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

server.js

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

控制台:

a
inside asyncCall 0

为什么卡住了?

推荐答案

可以传递给Meteor.wrapAsync的函数必须具有特定的签名:它们的参数必须以给定2个参数的回调结束:错误和结果.

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

您只能包装尊重此签名和行为的函数,这是从Node.JS继承的标准.

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

包装异步函数时,如果要处理潜在的错误,请不要忘记使用try/catch块.

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

这篇关于用wrapAsync陷入异步循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 18:13