2

I was wondering whether it would be ok to name the variable name for a promise just like the argument passed to a callback:

var dbItems = db.find();
dbItems.then(function(dbItems) {
    // Do some stuff with dbItems here...
});

I think that would be syntactically correct, but are there any arguments (like possible confusion or readability) against using this from the perspective of code style?

raffomania
  • 451
  • 4
  • 14
  • Just checking: Are both `dbItems` variables referring to the same object? If yes, then you don't need the parameter. You can just use the `dbItems` from the outer scope. If not, then you're shadowing (i.e. making inaccessible) the `dbItems` object from the outer scope. I'm not sure why you would want to do that. Variable shadowing should be avoided. – Šime Vidas Jun 30 '13 at 00:07
  • Looks to be completely legal javascript but might confuse someone, most likely yourself when you come to look at the code 6 months later. – Beetroot-Beetroot Jun 30 '13 at 00:12
  • @Beetroot-Beetroot thats what I was also thinking ;) Any recommendations on how to name them otherwise? Like, `dbItemsPromise` and `actualDbItems`? – raffomania Jun 30 '13 at 09:18
  • 1
    Raffomania, promise naming in general was discussed [here](http://stackoverflow.com/questions/14267346/javascript-naming-convention-for-promises) but didn't address your particular point. In your `.then()` chain, the outer and inner uses of `dbNames` will be different from each other - the outer *must* be a promise (it has a '.then()' method) and the inner (if everything has gone according to plan) *should* be the items themselves. IMHO, the promise should be named to reflect the fact that it is just that - a promise. You might name the inner to indicate whether it is an array or object. – Beetroot-Beetroot Jun 30 '13 at 11:11

1 Answers1

0
var dbItems = db.find();
dbItems.then(function(dbItems) {
    // Do some stuff with dbItems here...
});

Is the same thing as writing:

var dbItems = db.find();
dbItems.then(function(xxxxx) {
    var dbItems = xxxxx;
    // Do some stuff with dbItems here...
});

which means that inside the anonymous function, dbItems is a completely different thing, and you do not have access to the "outer" dbItems variable.

I don't usually recommend purchases on this site, but I feel that you could have very good use for this book. http://www.amazon.com/dp/0596517742

000
  • 26,951
  • 10
  • 71
  • 101
  • Thanks, I knew that ;) My question was more about if this is a good practice to do. When dealing with Promises, in almost every case you don't have to access the actual Promise variable from the callback (as it is already resolved when the callback is called). As the Promise and the argument for the callback mostly represent the same thing, I always felt an urge to name these two variables the same. – raffomania Jun 30 '13 at 09:17