1.0.1 • Published 4 years ago

node-promise-chain v1.0.1

Weekly downloads
-
License
ISC
Repository
-
Last release
4 years ago

node-promise-chain

用于解决node并发异步数据原子性问题

(将并发的请求缓存起来,达到设定数量或者时间后,批量执行)

例如:数据库中有一字段 count: 1

现有累加方法 cumulation,功能是将count 字段 +1

// 模拟用户请求,10次并发
for (let i = 0; i < 10; i++) {
  cumulation();
}

async function cumulation(query) {
  const data = await db.find(query)
  data.count++
  await db.update(data)
}

当同时有10个请求 cumulation() * 10,最终数据库保存结果为 count: 2

使用

const promiseChain = new PromiseChain(cumulation);

for (let i = 0; i < 10; i++) {
  //将原有调用 cumulation 的地方改为 push
  promiseChain.push("only_one_key", query);
}

async function cumulation(key, tasks) {
  // 并发请求会被收集合并为数组传入
  for (let i = 0; i < task.length; i++) {
    let data = await db.find(query);
    data.count++;
    await db.update(data);
  }
}

会为合并请求例如当请求100次或者5秒内无请求的时候的时候

您也可以修改这个配置

const promiseChain = new PromiseChain({ maxCount: 10, maxTime: 1000, callback: cumulation });

// key 用于区分不同的类型
// args 会被收集保存为数组
promiseChain.push(key, args)

高级用法

使用不同的key来区分合并

const promiseChain = new PromiseChain(cumulation);

for (let i = 0; i < 10; i++) {
  //将原有调用 cumulation 的地方改为 push
  promiseChain.push(query.id, query);
}

async function cumulation(key, tasks) {
  // 并发请求会被收集合并为数组传入
  for (let i = 0; i < task.length; i++) {
    let data = await db.find(query);
    data.count++;
    await db.update(data);
  }
}