在客户端上使用多个 Meteor 方法调用避免回调地狱 [英] Avoiding Callback Hell with Multiple Meteor Method calls on Client

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

问题描述

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

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

从 Meteor 的文档中我知道

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."

我知道我可以在服务器上创建另一个 Meteor 方法来执行使用 Meteor.async 包装的方法methodOne"、MethodTwo"、MethodThree",或者在没有回调的情况下按顺序执行.但是我担心这条路径会导致我的流星方法变得臃肿和纠缠,导致意大利面条式代码.我宁愿让每个 Meteor 方法保持简单,只做一项工作,并找到一种更优雅的方式来链接客户端上的调用.任何想法,有没有办法在客户端使用 Promises?

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 此答案将建议 Bluebird这实际上是运行真实基准测试时最快的promise库.而不是 a 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.

与另一个答案不同,这个答案也不会抑制错误,并且使函数返回承诺的成本微不足道,因为没有调用承诺构造函数.

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

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

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