承诺的JavaScript命名约定? [英] JavaScript naming convention for promises?

查看:69
本文介绍了承诺的JavaScript命名约定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为为JavaScript变量设置一个包含承诺的命名约定会很有用。我一般不喜欢或提倡超出编程语言标准的命名约定,但是在编程风格中,promises作为函数参数传递,通常难以一目了然地知道变量是持有承诺还是真实的东西。

I feel it would be useful to have a naming convention for JavaScript variables which hold a promise. I don't generally like or advocate naming conventions beyond programming language standards, but in the style of programming where promises are passed around as function arguments it's often hard to tell at a glance whether a variable holds a promise or the "real thing".

我个人使用 promiseOfFoo pFoo ,但是我发现前者有点冗长,后者给我回忆匈牙利语。

I've personally used promiseOfFoo and pFoo, but I find the former a bit verbose, and the latter gives me flashbacks from Hungarian.

是否有常用的约定?

推荐答案

这更多取决于你将如何使用它们,不是吗?

This depends more on how you're going to use them, doesn't it?

如果你的话代码如下:

var imageLoading = loadImage(url); // returns promise
imageLoading.done(showImage);

// imageLoading.done
// imageLoading.error
// imageLoading.then
// imageLoading.success
// imageLoading.fail
// ... whatever your library supports

然后,我可能会建议命名这个承诺的东西像现在时的动词...

Then, I might suggest naming the promise something like a present-tense verb...

但是如果你正在构建一个依赖于延迟对象的库

BUT if you're building a library which depends on deferred objects

// accepts a promise
var showImage = function (promise) {
    promise.done(function (img) { /* ...... */ });
};

然后将变量命名为名词没有什么特别的错误,只要对...有所了解哪些方法采取承诺而哪些方法不承诺。

Then there's nothing particularly wrong with naming the variable as a noun, so long as there's an understanding as to which methods take promises and which don't.

var image = loadImage(url); // returns promise
showImage(image);           // acts on promise

现在您的界面非常干净,您可以编写看起来100%的代码程序。
... buuuut,你需要知道哪些函数/方法使用promises和哪些使用对象。

Now your interfaces are really clean, and you can write code which looks 100% procedural. ...buuuut, you need to know which functions/methods use promises and which use objects.

如果你将promises作为回调传递,在对象内部方法,然后你可以愉快地命名他们承诺 tweetLoading dataParsing 或在特定情况下的任何有意义的事情。

If you are passing promises as callbacks, inside of object methods, then you can happily name them promise or tweetLoading or dataParsing or whatever makes sense within the context of that particular situation.

对于 showImage 的定义,我选择的参数是完全不称为的承诺,这样如果你正在做这个函数的工作,或者你需要调试一连串的东西,你可以看到第二个你看了它需要一个promise对象。

For the definition of showImage, the parameter I chose is flat-out called promise, so that if you're doing work on that function, or you needed to debug a chain of stuff, you could see the second you looked at it that it took a promise object.

这篇关于承诺的JavaScript命名约定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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