如何优雅地使用Promise.all批量并行加载游戏资源?
游戏资源并行加载的优化实现(TypeScript)
问题背景
开发游戏时需要并行加载不同类型的资源,现有两种实现方式都存在缺陷:
- 数组形式的
Promise.all依赖顺序,调整加载函数顺序后容易导致变量与资源不匹配:
let [ grassTexture, stoneTexture, waterTexture, birdSound, bellSound, choochooSound ] = await Promise.all([ loadGrassTexture(), loadStoneTexture(), loadWaterTexture(), loadBirdSound(), loadBellSound(), loadChoochooSound() ])
- 单独声明Promise再逐个await的写法代码冗余,维护性差:
let grassTexturePromise = loadGrassTexture() let stoneTexturePromise = loadStoneTexture() let waterTexturePromise = loadWaterTexture() let birdSoundPromise = loadBirdSound() let bellSoundPromise = loadBellSound() let choochooSoundPromise = loadChoochooSound() let grassTexture = await grassTexturePromise let stoneTexture = await stoneTexturePromise let waterTexture = await waterTexturePromise let birdSound = await birdSoundPromise let bellSound = await bellSoundPromise let choochooSound = await choochooSoundPromise
优化方案:使用对象形式的Promise.all
TypeScript支持传入对象给Promise.all,返回的结果会保留原对象的键值对应关系,既保证并行加载的效率,又彻底解决顺序匹配问题,同时自动适配不同资源的类型:
// 并行加载所有资源,结果与加载函数一一对应 const resources = await Promise.all({ grassTexture: loadGrassTexture(), stoneTexture: loadStoneTexture(), waterTexture: loadWaterTexture(), birdSound: loadBirdSound(), bellSound: loadBellSound(), choochooSound: loadChoochooSound() }); // 按需解构使用资源,类型自动推断 const { grassTexture, birdSound, choochooSound } = resources;
优势说明
- 无顺序依赖:通过键值对关联资源变量与加载函数,调整加载顺序或增减资源时不会出现匹配错误
- 类型安全:TypeScript会自动根据每个加载函数的返回值推断
resources对象中对应属性的类型,无需手动声明 - 代码简洁:相比单独声明Promise的写法,减少了大量冗余代码,结构更清晰
如果需要提前明确资源类型,也可以手动定义类型接口(可选,TypeScript会自动推断):
// 定义资源类型接口 interface GameResources { grassTexture: GrassTexture; stoneTexture: StoneTexture; waterTexture: WaterTexture; birdSound: AudioBuffer; bellSound: AudioBuffer; choochooSound: AudioBuffer; } // 加载并指定类型 const resources: GameResources = await Promise.all({ grassTexture: loadGrassTexture(), stoneTexture: loadStoneTexture(), waterTexture: loadWaterTexture(), birdSound: loadBirdSound(), bellSound: loadBellSound(), choochooSound: loadChoochooSound() });
内容的提问来源于stack exchange,提问作者mqnc
相关产品推荐
相关产品推荐

