避免回调地狱与多个流星法对客户端调用 [英] Avoiding Callback Hell with Multiple Meteor Method calls on Client

查看:141
本文介绍了避免回调地狱与多个流星法对客户端调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个Meteor.calls,其中每个方法依赖于另一个流星方法的响应

I have multiple Meteor.calls, where each methods depends on the response of another Meteor method.

客户端

Meteor.call('methodOne', function(err, resOne){
    if(!err){
        Meteor.call('methodTwo', resOne, function(err, resTwo){
            if(!err){
                Meteor.call('methodThree', resTwo, function(err, resThree){
                    if(err){
                        console.log(err);
                    }
                })
            }
        });
    }
});

从流星的文档,我知道

From Meteor's documentation I know

的方法称为客户端异步运行,所以你需要传递一个回调,以观察该调用的结果。

"Methods called on the client run asynchronously, so you need to pass a callback in order to observe the result of the call."

我知道我可以执行方法methodOne在服务器上创建另一个流星方法,MethodTwo','MethodThree使用Meteor.async,或先后无回调一起包裹。但我担心这条道路会导致我的流星方法来获取臃肿和纠缠,导致意大利面条code。我宁愿保留每个流星方法简单一个工作要做,找到链接在客户端调用的更优雅的方式。任何想法,有什么办法在客户端上使用的承诺?

I know I can create yet another Meteor Method on the server to execute methods 'methodOne', 'MethodTwo', 'MethodThree' wrapped using Meteor.async, or sequentially without the callback all together. But I am worried this path will cause my meteor methods to get bloated and entangled, leading to spaghetti code. I would rather keep each Meteor method simple with one job to do and find a more elegant way of chaining the calls on the client. Any ideas, is there any way to use Promises on the client?

推荐答案

由于对方的回答表明RSVP这个答案会建议蓝鸟 真正的基准的。而不是一个micro 基准并没有真正衡量任何有意义的东西。无论如何,我不会选择它的性能,我在这里采摘它,因为它也是最容易使用和具有最佳可调试。

Since the other answer suggests RSVP this answer will suggest Bluebird which is actually the fastest promise library when running real benchmarks. Rather than a micro benchmark that does not really measure anything meaningful. Anyway, I'm not picking it for performance, I'm picking it here because it's also the easiest to use and the one with the best debuggability.

不像其他的答案,这其中也并不燮preSS的错误,使函数返回一个承诺的成本是微不足道的,因为没有承诺的构造函数被调用。

Unlike the other answer, this one also does not suppress errors and the cost of making the function return a promise is marginal since no promise constructor is called.

var call = Promise.promisify(Meteor.call, Meteor);

var calls = call("methodOne").
            then(call.bind(Meteor, "methodTwo")).
            then(call.bind(Meteor, "methodThree"));

calls.then(function(resThree){
    console.log("Got Response!", resThree);
}).catch(function(err){
    console.log("Got Error", err); 
});

这篇关于避免回调地狱与多个流星法对客户端调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆