JavaScript naming convention for promises?

11,564

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.

Share:
11,564
jevakallio
Author by

jevakallio

Updated on June 18, 2022

Comments

  • jevakallio
    jevakallio almost 2 years

    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?