• async/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()
    

      

  • 相关阅读:
    数据结构相关概念
    树的创建与遍历
    Java探索之旅(18)——多线程(2)
    Java探索之旅(17)——多线程(1)
    Java Servlet 笔记4
    Java Servlet 笔记3
    Java Servlet 笔记2
    Java Servlet 笔记1
    JavaBean实现用户登陆
    基于SSE4和多核编程的电子相册的实现
  • 原文地址:https://www.cnblogs.com/zhaojia-dream/p/10118683.html
Copyright © 2020-2023  润新知