finally
function myDoStuff(params) {
return actuallyDoStuff(params)
.then(
(result) => { return "myTransformation " + result; }
)
.finally(cleanup);
}
function myDoStuff(params) {
return actuallyDoStuff(params)
.then(
(result) => { return "myTransformation " + result; }
)
.finally(() => cleanup().catch(() => {}));
}
// Note this takes only 10ms
function actuallyDoStuff(valueOrError, fail = false) {
return new Promise((resolve, reject) => {
setTimeout(fail ? reject : resolve, 10, valueOrError);
});
}
// Note this takes a full second
function cleanup(fail = false) {
return new Promise((resolve, reject) => {
setTimeout(fail ? reject : resolve, 1000, "cleanup done");
});
}
function myDoStuff(...params) {
return actuallyDoStuff(...params)
.then(
(result) => { return "myTransformation " + result; }
)
.finally(cleanup);
}
console.log("start with success");
myDoStuff("success")
.then(value => console.log("success", value))
.catch(error => console.log("error", error))
.finally(() => {
console.log("Notice how there was a 1,010ms delay, and that the result was from actuallyDoStuff, not cleanup");
console.log("start with error");
myDoStuff("error", true)
.then(value => console.log("success", value))
.catch(error => console.error("error", error))
.finally(() => {
console.log("Notice how there was a 1,010ms delay");
});
});
async
await
async function myDoStuff(params) {
try {
const result = await actuallyDoStuff(params);
return return "myTransformation " + result;
} finally {
await cleanup(); // Allows errors from cleanup
}
}
async function myDoStuff(params) {
try {
const result = await actuallyDoStuff(params);
return "myTransformation " + result;
} finally {
await cleanup().catch(() => {}); // Suppresses errors from cleanup
}
}
try
catch
async function myDoStuff(params) {
try {
const result = await actuallyDoStuff(params);
return "myTransformation " + result;
} finally {
try {
await cleanup()
} catch (e) { // As of ES2019, you could leave the `(e)` off
// That's already at Stage 4
}
}
}