【问题标题】:Meteor pattern for multiple method calls sequential callbacks多个方法调用顺序回调的流星模式
【发布时间】:2016-03-12 05:47:24
【问题描述】:

我在 Meteor 中编码时经常遇到这种模式,我发现自己进行了多个相互嵌套的方法调用——第一个方法触发,然后在回调中,第二个触发取决于第一个方法的结果,等等。是否有更好的模式来使用多个方法而无需在回调中嵌套方法调用?代码很快就会变得混乱。

Meteor.call('unsetProduct', product._id, omitObj, function(err, result) {
if(!err) {

    Meteor.call('editProduct', product._id, object, function(err, result) {
        if(!err) {

            //if no error, then continue to update the product template
                Meteor.call('editProductTemplate', self._id, obj, function(err, result) {
                    if(!err) {
                        //call some other method

                    }
                    else {
                        FormMessages.throw(err.reason, 'danger');
                    }
                }); 
        }
        else {
            FormMessages.throw(err.reason, 'danger');
        }
    });//end edit product

}
else {
    AppMessages.throw(err.reason, 'danger');
}

});`

【问题讨论】:

  • 您是否有理由不想将所有这些都放在一个服务器方法上?在可能的情况下,这确实是处理这些事情的最简单方法。
  • 使用发出相关错误的单一方法似乎更好。如果你想要一个更好的异步进程设计模式,你可以使用future/promise。

标签: javascript meteor methods


【解决方案1】:

看看reactive-method 包。我认为它完全符合您的需要:它将异步 Meteor.calls 包装到同步代码中。有了它,你的代码看起来会更干净,就像

try {
    const result = ReactiveMethod.call('unsetProduct', product._id, omitObj);
} catch (error) {
    AppMessages.throw(err.reason, 'danger');
}

try {
    const nestedResult = ReactiveMethod.call('editProduct', product._id, object);
} catch (error) {
    FormMessages.throw(err.reason, 'danger');
}

try {
    const evenMoreNestedResult = ReactiveMethod.call('editProductTemplate', self._id, obj);
} catch (error) {
    FormMessages.throw(err.reason, 'danger');
}

try 语句中添加一些逻辑会更好看。

【讨论】:

  • 我刚看到这个问题和我的一样,但是有一些其他的建议:stackoverflow.com/questions/28633187/…
  • 这个答案肯定很棒。但我个人不喜欢 promises(因为它们丑陋的点语法)并坚持使代码同步,或者至少看起来它是同步的。在 ES6 中,有 async/await 使代码在以异步方式执行时看起来是同步的。我相信 ReactiveMethod 开发人员很快就会采用它,因为在底层,它也是基于 Promises 的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多