这是写的回调更好的办法? [英] Which is a better way of writing callbacks?

查看:143
本文介绍了这是写的回调更好的办法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅仅通过看到我现在已经写了,我可以看到,一个是小很多,所以在的 code高尔夫 选项2 是更好的选择,但至于它是清洁,我preFER 选项1 。我真的爱社会的投入这一点。

选项1

  something_async({
    成功:功能(数据){
        的console.log(数据);
    },
    错误:功能(错误){
        的console.log(错误);
    }
});

选项2

  something_async(功能(错误数据){
    如果(错误){
        的console.log(错误);
    }其他{
        的console.log(数据);
    }
});


解决方案

很多人会发现选项#1更容易阅读和维护 - 为两个不同的目的两个不同的回调函数。它通常是由所有无极库,其中两个参数将被传递使用。当然,这个问题多个参数与选项对象是独立于(而对象<$ C $是非常有用的C> jQuery.ajax ,它没有任何意义 promise.then )。

不过,选项#2是 Node.js的约定(见的 NodeGuide )和由它影响了很多图书馆使用,例如著名的 async.js 。然而,这一惯例是分析讨论,顶谷歌的结果我发现是 WekeRoad:回调的NodeJS约定#1:什么是建议回调风格节点.js文件库?

的原因,并显示错误的参数的单一的回调函数是,它总是提醒显影剂来处理错误,这在服务器端应用特别重要。在客户方AJAX功能很多初学者不在乎忘了处理,例如错误,问自己为什么成功回调不会被调用。在另一方面,与承诺然后 -chaining是基于错误回调的可选性,它们传播到一个新的水平 - 当然,它仍然需要有钓到

Just by seeing what I've wrote now, I can see that one is much smaller, so in terms of code golf Option 2 is the better bet, but as far as which is cleaner, I prefer Option 1. I would really love the community's input on this.

Option 1

something_async({
    success: function(data) {
        console.log(data);
    },
    error: function(error) {
        console.log(error);
    }
});

Option 2

something_async(function(error,data){
    if(error){
        console.log(error);
    }else{
        console.log(data);
    }
});

解决方案

Many people will find option#1 easier to read and to maintain - two different callback functions for two different purposes. It is commonly used by all Promise Libraries, where two arguments will be passed. Of course, the question Multiple arguments vs. options object is independent from that (while the object is useful in jQuery.ajax, it doesn't make sense for promise.then).

However, option#2 is Node.js convention (see also NodeGuide) and used in many libraries that are influenced by it, for example famous async.js. However, this convention is discussable, top google results I found are WekeRoad: NodeJS Callback Conventions and Stackoverflow: What is the suggested callback style for Node.js libraries?.

The reason for the single callback function with an error argument is that it always reminds the developer to handle errors, which is especially important in serverside applications. Many beginners at clientside ajax functions don't care forget about error handling for example, asking themselves why the success callback doesn't get invoked. On the other hand, promises with then-chaining are based on the optionality of error callbacks, propagating them to the next level - of course it still needs to be catched there.

这篇关于这是写的回调更好的办法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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