0

Probably a very simple question, but here goes:

I'm using Bluebird promises, but I want to pass the value returned from one promise into another one as a parameter. My current code is thus:

Promise.props
  reports: @app.Reports.getReports()
  years: @app.Years.getYears()
.then (promised) =>
  console.log promised

But really I want to be able to use promised.years as the first parameter for getReports, so it would be something like reports: @app.Reports.getReports(promised.years)

I tried nesting promises but it exploded. I tried getting the years promise from inside the reports definition, but it exploded.

Any ideas?

Thanks!

Matt Fletcher
  • 8,182
  • 8
  • 41
  • 60
  • If suddenly you'll decide to use jQuery deferreds - there it's calles `pipe()` [link](http://api.jquery.com/deferred.pipe/); – Kiril Oct 15 '14 at 15:03
  • @Kiril: No one would be crazy enough to go from Bluebird to jQuery. Btw, `pipe()` is deprecated (since 1.8)! – Bergi Oct 15 '14 at 15:07

1 Answers1

1

Yes, nesting is the way to go here - without exploding, of course:

@app.Years.getYears()
.then (years) =>
    @app.Reports.getReports(years)
    .then (reports) ->
        console.log {years, reports}

You could not access promised.years in your getReports call, because it is not in scope - it's the parameter of the callback function that you pass in after having called getReports in the first place.

An alternative way to write this would be to construct the promises separately, and join them together with that Promise.props that you used:

yearsPromise = @app.Years.getYears()
reportsPromise = yearsPromise.then(@app.Reports.getReports)
Promise.props
    years: yearsPromise,
    reports: reportsPromise
.then (promised) ->
    console.log promised

(Notice that you cannot refer to another property in an object literal)

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Thanks! I like the look of the second option, but I don't understand at what point the parameter would be passed into `getReports` as it's a function reference... – Matt Fletcher Oct 15 '14 at 15:25
  • `Promise.join` does that for you - it waits for all arguments to resolve before calling your function. Actually, in this case it's an overcomplication, I'll replace it with a simpler mechanism – Bergi Oct 15 '14 at 15:30
  • Great, thanks! I decided to go with the first option after all as it gives me finer-grained control over what I pass in, even though I'm not a fan of nesting in general. I think my initial nesting problem was that I was trying to do two `.prop()`s - either way, it works now. Cheers again :) – Matt Fletcher Oct 15 '14 at 15:38
  • In case `getReports` is a method that uses `this` one can use `reportsPromise = yearsPromise.then(years => @app.Reports.getReports(years))` – Esailija Oct 17 '14 at 07:32