If you're just trying to retry 5 times in case of any error and then fail with an error after 5 errors and sqlConnection()
returns a promise that resolves when successful and rejects when there's an error, you can do something like this:
function delay(t) {
return new Promise(resolve => {
setTimeout(resolve, t)
})
}
function connect(retries = 5, pauseTime = 100) {
let cntr = 0;
function run() {
++cntr;
return sqlConnection().catch(err => {
console.log(err);
if (cntr < retries) {
return delay(pauseTime).then(run);
} else {
// let promise reject
throw err;
}
});
}
return run();
}
connect(5, 100).then(db => {
// connected here
}).catch(err => {
// failed to connect here
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…