我正在与嵌套的promise循环进行斗争,并且无法找到可行的解决方案。
我环顾四周,发现了这个:https://stackoverflow.com/a/29396005/3560729
promiseWhile函数似乎有我需要的东西,但是我无法让嵌套返回到外循环
promiseWhile:
function promiseWhile(predicate, action) {
function loop() {
if (!predicate()) return;
return Promise.resolve(action()).then(loop);
}
return Promise.resolve().then(loop);
}
嵌套循环:
let outerArray = outerArrayOfObjects;
let returnArray = [];
let returnArrayIndex = 0;
let outerIndex = 0;
let outerLength = outerArray.length;
let passObject = { };
promiseWhile(function() {
return outerIndex < outerLength;
}, function() {
let innerIndex = 0;
let innerLength = outerArray[outerIndex].innerArray.length;
passObject = {
innerObject: outerArray[outerIndex].innerArray[innerIndex],
returnArray: returnArray,
returnArrayIndex: returnArrayIndex
};
promiseWhile(function() {
return innerIndex < innerLength;
}, function() {
return new Promise(function(resolve, reject){
Promise.all([
promiseFunction1(innerObject),
promiseFunction2(innerObject),
promiseFunction3(innerObject),
])
.then(function (allMappings) {
passObject.returnArray[returnArrayIndex++] = {
"result1": allMappings[0],
"result2": allMappings[1],
"result3": allMappings[2]
}
offersIndex++;
return resolve(passObject)
})
.catch(function (err) {
offersIndex++;
return reject(err);
})
})
})
outerIndex++;
}).then(function() {
return resolve(passObject);
});
})
}
我认为我的主要问题是:我在哪里处理结果?我应该如何传递值,以便正确构建返回数组?
答案 0 :(得分:0)
上面的promiseWhile适用于执行操作,但不适合在嵌套循环中设置值并返回结果。
我最终选择了使用蓝鸟的方法:
var Promise = require('bluebird');
let outerArray = object.outerArray;
let returnArray = [];
let returnIndex = 0;
Promise.map(outerArray, function (outerArrayObject) {
let innerArray = outerArrayObject.innerArray;
let outerArrayValue = outerArrayObject.value;
Promise.map(innerArray, function (innerArrayObject) {
Promise.all([
PromiseFunction1(innerArrayObject),
PromiseFunction2(innerArrayObject),
PromiseFunction3(innerArrayObject),
])
.then(function (allResults) {
returnArray[returnIndex++] = {
"result1": allResults[0],
"result2": allResults[1],
"result3": allResults[2],
"result4": outerArrayValue,
}
return resolve(returnArray);
})
.catch(function (err) {
return reject(err);
})
})
})
.then(function () {
return resolve(returnArray)
}
).catch(function(err){
return reject(err);
}
)
}