zoukankan      html  css  js  c++  java
  • 并发执行异步事件,按顺序输出结果

     并发执行异步事件,按顺序输出结果,总耗时为数组中最大的数:

        const getData = async (num) => {
          return await new Promise((resolve) => {
            setTimeout(() => {
              resolve(num)
            }, num)
          })
        }
    
        //并发执行异步事件,按顺序输出结果,总耗时为数组中最大的数
        const order = async (nums) => {
          const promises = nums.map(async num => {
            return await getData(num)
          })
          for (const data of promises) {
            console.log(await data)
          }
          console.log(new Date())
        }
    
        const nums = [3000, 2000, 1000, 5000, 5000]
        console.log(new Date())
        order(nums)
        

    继发执行异步事件,按顺序输出结果,总耗时为数组中的数字之和:

       const getData = async (num) => {
          return await new Promise((resolve) => {
            setTimeout(() => {
              resolve(num)
            }, num)
          })
        }
    
        //继发执行异步事件,按顺序输出结果,总耗时为数组中的数字之和
        const order = async (nums) => {
          for (const num of nums) {
            const res = await getData(num)
            console.log(res)
          }
          console.log(new Date())
        }
    
        const nums = [3000, 2000, 1000, 5000, 5000]
        console.log(new Date())
        order(nums)
        

  • 相关阅读:
    Alpha 冲刺 (8/10)
    Alpha 冲刺 (7/10)
    Alpha 冲刺 (6/10)
    团队作业-随堂小测(同学录)
    Alpha 冲刺 (5/10)
    LeetCode-1
    c++向量
    软件工程实践总结作业
    个人作业——软件产品案例分析
    个人技术博客Alpha----Android Studio学习
  • 原文地址:https://www.cnblogs.com/xutongbao/p/14876273.html
Copyright © 2011-2022 走看看