异步请求网络方法
// 定义一个基本的异步网络请求方法
async function request<T>(method: string, url: string) {
try {
// 获取响应
let res = await fetch(url, { method })
let json: T = await res.json()
return json
} catch (error) {
console.log(error.message);
}
}
// 导出一个简单的GET请求方法
export function get<T>(url: string) {
return request<T>('GET', url)
}
async function run() {
// 等待异步请求的json数据,通过泛型标记返回的数据类型为 ISong[]
let songs = await request.get<ISong[]>('data/songs.json')
}
run()
模板替换方法
<script type="text/template" id="tpl">
<div class="song-item">
<div class="cover-wrap">
<img src="{{cover}}" class="cover-img">
<div class="cover-mask"></div>
<img src="imgs/cover_play.png" class="cover-play">
</div>
<div class="song-intro nowrap">
<a href="#" class="song-name">{{name}}</a>
<div class="song-singer nowrap">{{singer}}</div>
</div>
<div>{{time}}</div>
</div>
</script>
<script src="scripts/main.js" type="module"></script>
async function run() {
// 等待异步请求的json数据,通过泛型标记返回的数据类型为 ISong[]
let songs = await request.get<ISong[]>('data/songs.json')
let tpl = document.getElementById('tpl').innerHTML
let html = songs
.map(song => {
// 这里的song会自动推导为ISong类型
let time = timeFormat(song.interval)
let singer = song.singer
.map(item => `<a href="#" class="song-singer">${item}</a>`)
.join('<span class="song-sep">/</span>')
let result = tpl
.replace('{{name}}', song.name)
.replace('{{singer}}', singer)
.replace('{{time}}', time)
.replace('{{cover}}', song.cover)
return result
})
.join('')
document.querySelector('.songlist').innerHTML = html
}
run()