我玩过 Promise、Sequence、Exception、Callback 以了解它是如何工作的,最后制作了这段代码。
使用回调调用函数并将结果作为参数依次发送到另一个函数并捕获错误。
function firstFunction(par) {
return new Promise(function (resolve, reject) {
console.log("start " + par);
setTimeout(function (par) {
console.log(par);
resolve(par + 1);
}, 1000, par);
});
}
function secondFunction(par) {
return new Promise(function (resolve, reject) {
console.log("start " + par);
setTimeout(function (par) {
console.log(par);
try{
throw "Let's make an error...";
}
catch(err)
{
reject(err);
}
resolve(par + 1);
}, 1000, par);
})
}
function thirdFunction(par) {
return new Promise(function (resolve, reject) {
console.log("start " + par);
setTimeout(function (par) {
console.log(par);
resolve(par + 1);
}, 1000, par);
});
}
function CatchError(error) {
console.log("Exception: " + error);
}
//Break all chain in second function
function ChainBrake() {
firstFunction(1)
.then(secondFunction)
.then(thirdFunction)
.catch(CatchError);
}
//Log error and continue executing chain
function ChainContinue() {
firstFunction(1)
.catch(CatchError)
.then(secondFunction)
.catch(CatchError)
.then(thirdFunction)
.catch(CatchError);
}