图片加载

图片加载的功能,可以在图片加载完成后,执行一些操作。

代码配置

// 引入配置文件
import config from '../../index.md'

// 定义别名 mapKey, keyof typeof的作用是获取config.images的key的类型
type mapKey = keyof typeof config.images
// 定义一个map,key为mapKey,value为HTMLImageElement 并且暴露出去
export const image = new Map<mapKey, HTMLImageElement>()

// Object.entries()方法返回一个给定对象自身可枚举属性的键值对数组,其排列与使用for...in循环遍历该对象时返回的顺序一致
export const promises =  Object.entries(config.images).map(([key, value]) => {
  return new Promise(resolve => {
    // 创建一个img标签
    const img = document.createElement('img')
    img.src = value
    img.onload = () => {
      // 将img标签存入map中
      image.set(key as mapKey, img)
      // 执行resolve
      resolve(img)
    }
  })
})

其中,config.images是一个对象,里面存放了图片的路径,如下:

// index.md.js
import straw from "./src/static/images/straw/straw.png"
import water from "./src/static/images/water/water.gif"

export.default = {
  images: {
    straw,
    water
  }
}

Object.entries(config.images)返回的是一个数组,数组中的每一项都是一个数组,第一项是key,第二项是value,如下:

[
  ['straw', 'src/static/images/straw/straw.png'],
  ['water', 'src/static/images/water/water.gif']
]

使用

import { promises } from './image'

// 等待所有图片加载完成
async loadImages() {
  await Promise.all(promises)
}

然后就可以在图片加载完成后,执行一些操作了。

// 引入图片
import { image } from './image'

// 使用图片
const img = image.get('water')

网络请求

可以使用Promise的特性一次性发出多个请求,然后等待所有请求完成后,再执行一些操作。

代码配置

// 定义多个请求
const requests = [
  fetch('https://api.github.com/users/github'),
  fetch('https://api.github.com/users/github/followers')
]

// 等待所有请求完成
const responses = await Promise.all(requests)

需要注意的是,如果其中一个请求失败了,那么整个请求就会失败,所以需要使用try...catch来捕获错误。

try {
  const responses = await Promise.all(requests)
} catch (error) {
  console.log(error)
}

音频播放

假如要在一些地方播放音频,那么可以使用Promise来实现。

代码配置

import startAudio from '../static/music/start.wav'
import fireAudio from '../static/music/fire.wav'
import bulletAudio from '../static/music/blast.wav'

export default {
  el(type: string) : HTMLElement {
    // 创建一个audio标签
    let element = document.createElement('audio')
    element.src = type === 'start' ? startAudio : type === 'fire' ? fireAudio : bulletAudio
    return element
  },
  // 开始的时候播放
  async start() {
    const el = <HTMLAudioElement> this.el('start')
    // 添加到body中
    document.body.appendChild(el)
    // 音频播放
    await el.play()
  },
  // 开火的时候播放
  async fire() {
    const el = <HTMLAudioElement> this.el('fire')
    // 音频播放
    await el.play()
  },
  // 子弹爆炸的时候播放
  async blast() {
    const el = <HTMLAudioElement> this.el('blast')
    // 音频播放
    await el.play()
  }
}

使用

import audio from './audio'

// 开始的时候播放
async start() {
  await audio.start()
}
Last Updated:
Contributors: huangdingxin, 黄定鑫