guyu/common/system/system.js
2025-07-23 20:52:57 +08:00

38 lines
1.5 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { preloadHomeData } from '@/common/server/home'
import { getConfig } from '@/common/server/config';
/**
* 应用初始化函数,带有超时控制
* @param {number} timeoutMs - 超时时间(毫秒)
* @returns {Promise<boolean>} - 返回Promisetrue表示初始化成功false表示失败
*/
export const appInit = async (timeoutMs = 5000) => {
try {
//获取系统配置
const getConfigTask = getConfig();
//获取首页关键数据
const homeTask = preloadHomeData();
// 2. 创建一个会在指定时间后拒绝的Promise用于超时控制
const timeoutPromise = new Promise((_, reject) =>
setTimeout(() =>
// 当超时触发时拒绝Promise并返回超时错误
reject(new Error(`初始化获取超时 (${timeoutMs}ms)`)),
timeoutMs
)
);
// 3. 使用Promise.race让首页获取数据和超时Promise"赛跑"
// 哪个先完成(成功或失败)就采用哪个的结果
await Promise.race([
// 使用Promise.all包装是为了保持一致性
Promise.all([getConfigTask, homeTask]),
timeoutPromise
]);
// 4. 如果没有超时全部获取成功返回true
return true;
} catch (error) {
// 5. 错误处理(可能是超时错误或首页获取失败)
console.error('初始化任务失败:', error);
// 6. 返回false表示初始化失败
return false;
}
}