gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 16:39:30 28 4
gpt4 key购买 nike

我正在尝试使用 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com