我是新来的承诺。我试图使用promise向mysql db发送查询。在一些查询之后,我将使用查询的结果,进行一些计算,然后将输出用作下一个查询的一些参数。看起来如下:
firstQuery(). then(secondQuery). then(thirdQuery). then(fourthQuery). ...
比如说,在第四个查询中,我需要使用来自firstQuery和secondQuery的结果,并且还会有一些额外的计算。我该怎么做?
我知道我可以通过将参数传递给函数来获得前一个承诺的结果:
then(thirdQuery). then(cal("I can only get output from thirdQuery here")). then(fourthQuery("pass output from cal"))
在这种情况下,我没有任何Promise优于回调的优点,因为我总是可以编写一个函数来简化重复的回调。
答案 0 :(得分:0)
在这种非常常见的情况下,您可以移动每个then
外部承诺的结果,然后可以在剩余的then
块中访问它们。
例如:
function first() { ... }
function second() { ... }
function third() { ... }
function fourth(firstValue, secondValue) { ... }
var firstResponse, secondResponse;
first()
.then(function(_firstResponse) {
firstResponse = _firstResponse;
return second();
})
.then(function(_secondResponse) {
secondResponse = _secondResponse;
return third();
})
.then(function() {
return fourth(firstResponse, secondResponse);
})
答案 1 :(得分:0)
如果你可以重写firstQuery,secondQuery等你可以做这样的事情
function firstQuery(allResult = {}) {
return doTheQuery()
.then(result => {
allResult.first = result;
return result;
});
}
function secondQuery(allResult = {}) {
return doTheQuery()
.then(result => {
allResult.second = result;
return result;
});
}
function thirdQuery(allResult = {}) {
return doTheQuery()
.then(result => {
allResult.third = result;
return result;
});
}
function fourthQuery(allResult = {}) {
return doTheQuery(allRessult.first, allResult.second)
.then(result => {
allResult.fourth = result;
return result;
});
}
然后你可以写使用
firstQuery()
.then(secondQuery)
.then(thirdQuery)
.then(fourthQuery)
.then ...
最终结果将是一个对象,其中包含{first,second,third,4th}属性中所有查询的值
当然,如果您只想要第四个查询结果
firstQuery()
.then(secondQuery)
.then(thirdQuery)
.then(fourthQuery)
.then(result => result.fourth)
.then ...
答案 2 :(得分:0)
通常,您应该将promises视为值和依赖项,而不是控制执行流的方法。一个可靠的选择是组织你的代码:
copy($original_file, $new_user_folder);
基本上我猜这里的关键是知道bluebird库的var firstResult = firstQuery();
var secondResult = firstResult.then(secondQuery);
var thirdResult = secondResult.then(thirdQuery);
var fourthResult = Promise.join(firstResult, secondResult, fourthQuery);
方法(其他存在可用于相同效果的方法),但另一个好处是我发现这种代码更少错误倾向于混合原始变量和承诺变量。
另请注意,这是可能的,因为在同一个承诺上多次调用join
是完全可以的。