async/await - 8.在for循环中正确的使用await
async/await - 8.在for循环中正确的使用await
const fetch = require('node-fetch') const bluebird = require('bluebird') async function getZhihuColumn(id) { await bluebird.delay(1000) const url = `https://zhuanlan.zhihu.com/api/columns/${id}` const response = await fetch(url) return await response.json() }
循环中的串行
const showColumnInfo = async() => { console.time('showColumnInfo') const names = ['qianduanzhidian', 'FrontendMagazine'] for (const name of names) { const column = await getZhihuColumn(name) console.log(`name:${column.name}`) console.log(`description:${column.description}`) } console.timeEnd('showColumnInfo') // 4757.181ms } showColumnInfo()
循环中的并行
const showColumnInfo = async() => { console.time('showColumnInfo') const names = ['qianduanzhidian', 'FrontendMagazine'] const promises = names.map(x => getZhihuColumn(x)) for (const promise of promises) { const column = await promise console.log(`name:${column.name}`) console.log(`description:${column.description}`) } console.timeEnd('showColumnInfo') // 2615.484ms } showColumnInfo()