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".
I've personally used promiseOfFoo
and pFoo
, but I find the former a bit verbose, and the latter gives me flashbacks from Hungarian.
Is there a commonly used convention?
This depends more on how you're going to use them, doesn't it?
If your code looks like:
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
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.
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.
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.
I don't know of a public convention but have used the following in my own code :
var dfrd
: a Deferred object (I've don't recall ever needing two or more in the same scope)
var p
: a Promise
var p_foo
: one of several named Promises
var promises
: an array or plain object containing Promises
The exception is a jqXHR
object, which I will name var jqXHR
(again, I don't recall ever needing two or more in the same scope).