我已经将我的代码重组为承诺,并构建了一个由多个回调组成的精彩长扁平承诺链.then().最后我想返回一些复合值,并且需要访问多个中间承诺结果.但是,序列中间的分辨率值不在最后一个回调的范围内,我该如何访问它们?
function getExample() {
return promiseA(…).then(function(resultA) {
// Some processing
return promiseB(…);
}).then(function(resultB) {
// More processing
return // How do I gain access to resultA here?
});
}
Run Code Online (Sandbox Code Playgroud) 我的问题是我不知道如何知道动态promise数组何时解决了所有的promise.
这是一个例子:
var promiseArray = [];
promiseArray.push(new Promise(){/*blablabla*/});
promiseArray.push(new Promise(){/*blablabla*/});
Promise.all(promiseArray).then(function(){
// This will be executen when those 2 promises are solved.
});
promiseArray.push(new Promise(){/*blablabla*/});
Run Code Online (Sandbox Code Playgroud)
我这里有问题.当前Promise.all两个承诺被解决时,行为将被执行,但是,在这两个承诺被解决之前,第三个承诺被添加并且这个新承诺将不被考虑.
所以,我需要的是:"嘿Promise.all,你有一个动态数组来检查".我该怎么做?
请记住,这只是一个例子.我知道我可以将线Promise.all移到最后一行,但实际上新的承诺是在另一个承诺解决时动态添加的,而新的承诺也可以添加新的承诺,因此,它是一个非常动态的数组.
我拥有的真实用例是这样的:
另一个难的例子:
var allPromises = [];
allPromises.push(new Promise(function(done, fail){
mongoDB.connect(function(error){
//Because mongoDB works with callbacks instead of promises
if(error)
fail();
else
ajax.get('/whatever').then(function(){
if (somethingHappens) {
allPromises.push(new Promise(function(done, fail){ //This promise never will be take in account
// bla bla …Run Code Online (Sandbox Code Playgroud)