2014-12-24 42 views
0

我想用Javascript使用承諾API做一些提取,然後使用我剛剛提取的所有值。喜歡的東西...鏈承諾和使用所有變量

// 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); 
}); 

問題是thing1thing2走出去的範圍在函數調用之後。我如何在最後的then函數中使用它們?

回答

2

您可以將thing1thing2保存在聲明範圍上方的變量中。

這樣,

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); 
});