我很难尝试停止promise中的循环。这是我的方法。这有什么问题吗?
Promise.all(myArray.map((obj) => {
this.someFunction(obj);
}))
这是我调用的函数。
someFunction(){
return new Promise(function (resolve, reject) {
....
reject()
})}
答案 0 :(得分:0)
我已经更新了代码,它已经过测试,并且可以与我提供的模拟数据一起在我的机器上运行。我不确定您的其余代码的结构如何,但这是这样的:哦,您不能突围地图,但是我们将使用一个简单的for循环,因为我们可以突围一下:
function someFunction(){
return new Promise(function (resolve, reject) {
// I will be rejeccting a boolean
// If you are resolving something, resolve it as true
reject(false)
})}
async function shouldStopLoop(){
// the boolean will come here
// if it is false, the catch block will return
// if it is true, the try block will return
let stopLoop = null;
let result = null;
try {
result = await someFunction();
return result
} catch(error) {
stopLoop = error;
return stopLoop;
}
}
function mayReturnPromiseAll() {
let myArray = ['stuf to loop over...']
let arraytoGoInPrimiseAll = [];
// Array.prototype.map cannot be stopped
// Thats why we will use a for loop and we will push the data we need
// into another array
for (var i = 0; i < myArray.length; i++) {
if (!this.someFunction(obj)) {
break;
} else {
// push things in arraytoGoInPrimiseAll
}
}
if(arraytoGoInPrimiseAll.length > 0){
return Promise.all(arraytoGoInPrimiseAll)
} else {
// do something else
}
};
答案 1 :(得分:0)
尝试一下:
const arrayOfFunctions = myArray.map(obj => this.someFunction(obj))
Promise.all(arrayOfFunctions).then(values => {
console.log(values);
}).catch(error => {
console.log(error)
});