发布于 2020-03-25 19:31:43
可以说答案是否定的,但你至少有几个选择:
try/finally来实现。Re try/finally,你在评论中说:是的,除非我不想使用try catch块,因为它们可能很昂贵。
不怎么有意思。抛出异常的开销很大,而进入try块则不是。finally块有轻微的开销,但我最近不得不在几个现代引擎中测量这一点,这真的是令人惊讶的微不足道。
try/finally更昂贵。对于多个(否则将需要嵌套的try/finally块),那么,您必须找出答案。FWIW,一些例子:
在try/finally中执行一次清理
function example() {
try {
console.log("hello");
} finally {
console.log("world");
}
}
example();
try/finally中的多重清理
function example() {
try {
console.log("my");
try {
console.log("dog");
} finally {
console.log("has");
}
} finally {
console.log("fleas");
}
}
example();
通过赋值函数进行单次清理:
function example() {
let fn = null;
fn = () => console.log("world");
console.log("hello");
if (fn) { // Allowing for the above to be conditional, even though
// it isn't above
fn();
}
}
example();
try/finally中的多重清理
function example() {
const cleanup = [];
cleanup.push(() => console.log("has"));
console.log("my");
cleanup.push(() => console.log("fleas"));
console.log("dog");
cleanup.forEach(fn => fn());
}
example();
或者以另一种顺序:
function example() {
const cleanup = [];
cleanup.push(() => console.log("fleas"));
console.log("my");
cleanup.push(() => console.log("has"));
console.log("dog");
while (cleanup.length) {
const fn = cleanup.pop();
fn();
}
}
example();
https://stackoverflow.com/questions/60847836
复制相似问题