12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- /*
- * @Author: fxs bjnsfxs@163.com
- * @Date: 2024-08-31 14:51:20
- * @LastEditors: fxs bjnsfxs@163.com
- * @LastEditTime: 2024-10-14 16:11:04
- * @FilePath: \Game-Backstage-Management-System\src\utils\resource\index.ts
- * @Description:
- *
- */
- // 缓存对象
- const resourceCache: Record<string, string> = {}
- /**
- * 加载资源并且缓存这个资源
- * 如果资源已经被加载过,则直接返回缓存中的资源
- *
- * @param url - 资源的加载路径
- * @returns 返回blob对象的url
- */
- export const loadResource = async (url: string): Promise<string> => {
- // 检查是否已经存储了这个资源,已经缓存了就直接返回
- if (resourceCache[url]) {
- return Promise.resolve(resourceCache[url])
- }
- // 如果没有缓存则去请求这个资源,并将他转为bolb对象,并且缓存blob对象的ulr
- try {
- const resourceBlob = await fetch(url)
- if (!resourceBlob.ok) throw new Error(`资源加载失败: ${url}`)
- const blob = await resourceBlob.blob()
- const objectURL = URL.createObjectURL(blob)
- resourceCache[url] = objectURL
- return objectURL
- } catch (err) {
- console.log(err)
- throw new Error('资源加载失败')
- }
- }
- /**
- * @description: 初始化加载所有的资源
- * @param {Record} resourceObj 请求的url对象,键值都为string,key为资源的名称,值为资源的请求地址
- * @return {*} 返回一个包含了key和blobURL的对象,用来表示所有资源的请求情况
- */
- export const initLoadResouce = (
- resourceObj: Record<string, string>
- ): Promise<Record<string, string>> => {
- // 获取所有的 URL 列表
- let urlList = Object.entries(resourceObj) // [key, url] 格式
- // 创建请求列表
- let reqList: Promise<[string, string | null]>[] = urlList.map(([key, url]) =>
- loadResource(url)
- .then((objectURL) => [key, objectURL] as [string, string])
- .catch(() => [key, null] as [string, string | null])
- )
- // 使用 Promise.all 处理所有请求
- return Promise.all(reqList).then((results) => {
- // 创建返回对象
- let resultObj: Record<string, string> = {}
- results.forEach(([key, value]) => {
- if (value !== null) {
- resultObj[key] = value // 如果成功,存入结果对象中
- }
- })
- return resultObj // 返回所有成功的资源
- })
- }
|