【前端】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
    }
}
相关推荐
VBA63375 小时前
VBA即用型代码手册:利用函数保存为PDF文件UseFunctionSaveAsPDF
开发语言
say_fall5 小时前
C语言编程实战:每日刷题 - day2
c语言·开发语言·学习
合作小小程序员小小店6 小时前
web开发,在线%超市销售%管理系统,基于idea,html,jsp,java,ssh,sql server数据库。
java·前端·sqlserver·ssh·intellij-idea
上去我就QWER6 小时前
Qt快捷键“魔法师”:QKeySequence
开发语言·c++·qt
不爱学英文的码字机器7 小时前
重塑 Web 性能:用 Rust 与 WASM 构建“零开销”图像处理器
前端·rust·wasm
浩星7 小时前
react的框架UmiJs(五米)
前端·javascript·react.js
Pluto_CSND8 小时前
Java中的静态代理与动态代理(Proxy.newProxyInstance)
java·开发语言
子醉9 小时前
推荐一种适合前端开发使用的解决本地跨域问题的办法
前端
Niyy_9 小时前
前端一个工程构建多个项目,记录一次工程搭建
前端·javascript
惊讶的猫10 小时前
LSTM论文解读
开发语言·python