【前端】js 多个并行的Promise阻塞工具 指定同时执行数量

"多线程"Promise 工具类

vue

that = this

或者用 全局变量

map = {count:0}

复制代码
//阻塞并获取额度
await WTool.Thread.sleepLimit(that, '变量名称', 500)

await WTool.Thread.sleepLimit(map, 'count', 500)

复制代码
  Thread:{
    /**
     * 阻塞x毫秒
     * 使用方法
     * await sleep(5000)  等待5秒
     * @param time
     * @returns {Promise<void>}
     */
    async sleep(time){
      await new Promise(resolve => setTimeout(resolve, time))
    },
    /**
     * 阻塞获取额度
     * 使用方法
     * await sleepLimit(that, 字段, 1000)
     * @param _vm     that
     * @param field   字段
     * @param time   多久判断一次
     * @returns {Promise<boolean>}
     */
    async sleepLimit(_vm, field, time){
      if(time){
        time = 500
      }
      let flag = true
      while(flag){
        if(_vm[field] > 0){
        // if(_vm[field].length > 0){
          //睡眠等待
          await WTool.Thread.sleep(time);

          //有额度了
          flag = false
          _vm[field]--
          // _vm[field].shift()
          console.log('有额度了,获取名额之后:',_vm[field])
          return true
        }else{
          //睡眠等待
          await WTool.Thread.sleep(time);
        }
      }

    },
    /**
     * 等待额度释放完毕
     * 使用方法
     * await join(that, 字段, 1000)
     * @param _vm     that
     * @param field   字段
     * @param time   多久判断一次
     * @returns {Promise<boolean>}
     */
    async join(_vm, field, realCount, time){
      if(time){
        time = 2000
      }
      let flag = true
      while(flag){
        if(_vm[field] >= realCount){
        // if(_vm[field].length >= realCount){
          console.log('所有额度释放完毕:',_vm[field])
          //有额度了
          flag = false
          return true
        }else{
          //睡眠等待
          await WTool.Thread.sleep(time);
        }
      }

    }

  },

核心就是阻塞 等待其他完成

其他方案

参考

浅谈JS阻塞方式怎么实现异步任务队列?-云搜网 (27ka.cn)

javascript 复制代码
let queue = []
let index = 0
function clickMe() {
    queue.push({
        name: 'click',
        index: index++
    })
}
run()
async function run() {
    while (true) {
        if (queue.length > 0) {
            let obj = queue.shift()
            let res = await request(obj.index)
            console.log('已处理事件' + res)
        } else {
            await wait(500)
            console.log('----- 队列空闲中 -----')
        }
    }
}
// 通过setTimeout模拟异步请求
function request(index) {
    return new Promise(function (resolve, reject) {
        setTimeout(() => {
            resolve(index)
        }, 1000)
    })
}

function wait(time) {
    return new Promise(function (resolve) {
        setTimeout(() => {
            resolve()
        }, time)
    })
}

其他方案

javascript 复制代码
// 异步请求队列 
const queue = []
// 用来模拟不同的返回值 let index = 0
// 标志是否正在处理队列中的请求
let running = false
// 使用setTimeout模拟异步请求
function request(index) {
    return new Promise(function (resolve) {
        setTimeout(() => {
            resolve(index)
        }, 1000)
    })
}
// 连续点击,触发异步请求,加入任务队列
function clickMe() {
    addQueue(() => request(index++))
}
// 当队列中任务数大于0时,开始处理队列中的任务 
function addQueue(item) {
    queue.push(item)
    if (queue.length > 0 && !running) {
        running = true
        process()
    }
}

function process() {
    const item = queue.shift()
    if (item) {
        item().then(res => {
            console.log('已处理事件' + res)
            process()
        })
    } else {
        running = false
    }
}
相关推荐
excel4 小时前
ES6 中函数的双重调用方式:fn() 与 fn\...``
前端
可乐爱宅着4 小时前
全栈框架next.js入手指南
前端·next.js
你的人类朋友6 小时前
什么是API签名?
前端·后端·安全
会豪8 小时前
Electron-Vite (一)快速构建桌面应用
前端
中微子8 小时前
React 执行阶段与渲染机制详解(基于 React 18+ 官方文档)
前端
唐某人丶8 小时前
教你如何用 JS 实现 Agent 系统(2)—— 开发 ReAct 版本的“深度搜索”
前端·人工智能·aigc
中微子8 小时前
深入剖析 useState产生的 setState的完整执行流程
前端
遂心_8 小时前
JavaScript 函数参数传递机制:一道经典面试题解析
前端·javascript
小徐_23338 小时前
uni-app vue3 也能使用 Echarts?Wot Starter 是这样做的!
前端·uni-app·echarts
RoyLin8 小时前
TypeScript设计模式:适配器模式
前端·后端·node.js