I am struggling with promises
having the following snippet:
Promise.resolve()
.then(a("OK1"))
.then(a("OK2"))
.then(a("OK3"))
.then(a("OK4"))
.then(a("OK5"))
.then(function() {
console.log("FINISH");
})
.catch(function(e) {
console.log("ERROR: " + e);
});
function a(i) {
return new Promise(function(resolve, reject) {
if(i == "OK4") {
console.log("THROW");
throw('Error'); //This does not happen
reject();
return;
}
if(i == "OK2") {
reject()
return;
}
console.log(i);
resolve();
});
}
i want to be able to reject a promise - then the next .then
is executed ("OK3")
but i am unable to throw exceptions - i want to trigger the .catch on "OK4"
OK4 - is rejected and not outputted, but OK5 still gets executed - is there a way arround it?
this would be my expected output:
OK1
OK3
ERROR: ....
答案 0 :(得分:1)
正如Bergi所提到的,您在每个.then
上传递的参数会立即运行该函数并返回一个promise。 promise链需要引用它可以在以后运行的函数。
如果要使用参数运行函数,可以将其包装在匿名函数中,以便promise链可以在以后运行匿名函数。
a("OK1")
.then((res)=>{
return a("OK2")
})
.then((res)=>{
return a("OK3")
})
.then((res)=>{
return a("OK4")
})
.then((res)=>{
return a("OK5")
})
.then(()=>{
console.log("FINISH");
})
.catch(function(e) {
console.log("ERROR: " + e);
});
function a (i) {
return new Promise(function(resolve, reject) {
if(i == "OK4") {
console.log("THROW");
throw new Error(i); //This does not happen
}
if(i == "OK2") {
return reject(new Error(i))
}
setTimeout(function () {
console.log(i);
resolve(i);
}, 100)
});
}
传递一个最终会返回一个promise的函数是可以的。该函数将传递前一个promise解析的值。
b(1)
.then(b)
.then(b)
.then(b)
.then((res) => {
console.log("FINISH",res);
})
.catch(function (e) {
console.log("ERROR: " + e);
});
function b (i) {
return new Promise(function (resolve, reject) {
console.log(i)
resolve(i+1)
})
}