描述
我有这个函数可以创建加载效果:
/**
* @template T
* @param {Promise<T>} promise
* @param {number} duration
* @param {number} delay
*/
Window.prototype.load = async function (promise, duration = 200, delay = 0) {
const dialogLoader = document.getElement(HTMLDialogElement, `dialog.loader`);
dialogLoader.showModal();
await dialogLoader.animate([
{ opacity: `0` },
{ opacity: `1` },
], { duration: duration, fill: `both` }).finished;
try {
const value = await promise;
await dialogLoader.animate([
{ opacity: `1` },
{ opacity: `0` },
], { duration: duration, fill: `both`, delay: delay }).finished;
dialogLoader.close();
return value;
} catch (error) {
await dialogLoader.animate([
{ opacity: `1` },
{ opacity: `0` },
], { duration: duration, fill: `both`, delay: delay }).finished;
dialogLoader.close();
throw error;
}
};
有点令人困惑的是, intry
和 incatch
几乎执行了相同的代码:
await dialogLoader.animate([
{ opacity: `1` },
{ opacity: `0` },
], { duration: duration, fill: `both`, delay: delay }).finished;
dialogLoader.close();
问题
有什么办法可以缩短这段重复的代码吗?如果是这样,那又如何呢?
结果是这样的: