The correct way to pass down variables within Bluebird?

For example:

redis.get('xfers:Turkey').then( data => {
    var GAME_ID = 25;
    return [returnPromise, returnPromise2]
}).spread( (success, success2) => {
    //GAME_ID here is undefined
});

However, you can do:

redis.get('xfers:Turkey').then( data => {
    var GAME_ID = 25;
    return [returnPromise, returnPromise2, GAME_ID]
}).spread( (success, success2, GAME_ID) => {
    //GAME_ID here is passed
});

Which works fine, I just feel like I am doing something wrong. If I have a lot of variables that are created, I would need to pass down lot of arguments. (For each consecutive chain as well) -- I was curious if there is a more intuitive approach, thank you!

Upvotes: 1

Views: 48

Answers (1)

dodev
dodev

Reputation: 151

First, to answer your question - is there a more intuitive way for passing values down a promise chain - no, in my experience 'returning' the value as the next callback argument is the best you can get.

Never the less if you use those basic tools wisely you can achieve good clarity and maintainability of your code. Here are some basic rules I use when writing promise chains:

  1. Variables that are not dependent on the result of any of the promises should be set locally in the closure. In your example GAME_ID looks like a good candidate for that.
  2. If possible, execute one asynchronous action at a time. Meaning that returning an array and then 'spreading' is less readable than having a simple one item pipeline.
  3. Use a promise only when you really have to execute something asynchronously. Sometimes it is compelling to return a synchronously computed value and pass it as an argument down the chain, but you should remember that promises are not free and come at a cost of an event loop tick.

Upvotes: 1

Related Questions