我正在开发一款游戏,我在代码中有一个位置可以并行加载所有资源。目前它看起来像这样:
let [
grassTexture,
stoneTexture,
waterTexture,
skyTexture,
sandTexture,
woodTexture,
carpetTexture,
paperTexture,
steelTexture
] = await Promise.all([
loadGrassTexture(),
loadStoneTexture(),
loadWaterTexture(),
loadSkyTexture(),
loadSandTexture(),
loadWoodTexture(),
loadCarpetTexture(),
loadPaperTexture(),
loadSteelTexture()
])
但这并没有让我觉得设计得特别好,因为很容易搞乱顺序,如果结果与相应的函数调用在同一行,那就更好了。我看到的另一个选择是:
let grassTexture = loadGrassTexture()
let stoneTexture = loadStoneTexture()
let waterTexture = loadWaterTexture()
let skyTexture = loadSkyTexture()
let sandTexture = loadSandTexture()
let woodTexture = loadWoodTexture()
let carpetTexture = loadCarpetTexture()
let paperTexture = loadPaperTexture()
let steelTexture = loadSteelTexture()
await grassTexture
await stoneTexture
await waterTexture
await skyTexture
await sandTexture
await woodTexture
await carpetTexture
await paperTexture
await steelTexture
但这也好不了多少。有一些惯用的方法可以做到这一点吗?
不要为每个资源使用单独的变量,而是将它们放入由资源名称键入的对象中。
然后您可以使用
Promise.all()
,然后循环填写值。
const textures = {
grass: loadGrassTexture(),
stone: loadStoneTexture(),
// ...
};
let results = await Promise.all(Object.values(textures));
Object.keys(textures).forEach((key, i) => textures[key] = results[i]);