【前端】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
    }
}
相关推荐
杨啸_新房客1 分钟前
如何优雅的设置公司的NPM源
前端·npm
ohyeah1 分钟前
深入理解 JavaScript 中的继承与 instanceof 原理
前端·javascript
linhuai2 分钟前
flutter如何实现有登陆权限管理
前端
crary,记忆3 分钟前
React 之 useEffect
前端·javascript·学习·react.js
urkay-3 分钟前
Android getDrawingCache 过时废弃
android·java·开发语言·kotlin·iphone·androidx
小oo呆6 分钟前
【学习心得】Python好库推荐——pipx
linux·开发语言·python
CoderYanger9 分钟前
C.滑动窗口-求子数组个数-越短越合法——3258. 统计满足 K 约束的子字符串数量 I
java·开发语言·算法·leetcode·1024程序员节
BD_Marathon11 分钟前
【JavaWeb】HTML常见标签——标题段落和换行
前端·html
小飞侠在吗14 分钟前
vue OptionsAPI与CompositionAPI
前端·javascript·vue.js
幽络源小助理23 分钟前
《已调试》SpringBoot景区寄存管理系统源码 - 免费JavaWeb项目下载 | 幽络源
java·开发语言·spring boot