javascript - 链式 promise 并使用所有变量

标签 javascript promise

我正在尝试使用 Promises API 通过 Javascript 进行一些获取,然后使用我刚刚获取的所有值。类似...

// 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功能?

最佳答案

您可以将 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);
});

关于javascript - 链式 promise 并使用所有变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27631624/

相关文章:

javascript - 如何组合多个 getServerSideProps 包装器?

javascript - 使用 Protractor 自动生成用于测试表单的字段值

javascript - 如何实现本例中的自定义 jQuery 页面滚动 api?

javascript,promises,如何在 then 范围内访问变量 this

javascript - 导出链式 promise 的返回值

javascript - 如何在 node.js 中实际使用 Q Promise?

javascript - Coffeescript Promise 与 Jquery Post

javascript - Netsuite Script beforeLoad 记录未被修改

c# - 如何以编程方式将站点固定到 Windows 8 中的启动屏幕

javascript - Nodejs 一个接一个地运行异步函数