0

I'm trying to do a few fetches with Javascript using a Promises API, and then use all of the values I just fetched. Something like...

// Use an Id to find thing 1, use thing 1 Id to find thing2, use thing 2 id to find thing 3, 
// then use all of them.
thing1model.findById(thing1id).then(function(thing1) {
    return thing2model.findById(thing1.id);
}).then(function(thing2) {
    return thing3model.findById(thing2.id);
}).then(function(thing3) {
    // Here I want to use all of thing1, thing2, thing3...
    someFunction(thing1, thing2, thing3);
}).catch(function(err) {
    console.log(err);
});

The problem is thing1 and thing2 go out of scope after the function call. How can I use them in the last then function?

Kevin Burke
  • 61,194
  • 76
  • 188
  • 305

1 Answers1

2

You can save thing1 and thing2 in variables which are declared in scope above your chain.

Like this,

var thing1Data, thing2Data
thing1model.findById(thing1id).then(function(thing1) {
    thing1Data = thing1
    return thing2model.findById(thing1.id);
}).then(function(thing2) {
    thing2Data = thing2
    return thing3model.findById(thing2.id);
}).then(function(thing3) {
    someFunction(thing1Data, thing2Data, thing3);
}).catch(function(err) {
    console.log(err);
});
Kelsadita
  • 1,038
  • 8
  • 21