New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

tasks.promise

Package Overview
Dependencies
Maintainers
1
Versions
3
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

tasks.promise

一个可以处理并发和重试的 promise 库

latest
npmnpm
Version
0.2.1
Version published
Maintainers
1
Created
Source

使用场景

一个用于处理大量异步任务的短小精悍库,支持并发数和重试次数的配置

快速开始

安装

npm install tasks.promise

例子


const { runAll } = require('tasks.promise');

// 一个可能随机失败的 Promise
function getPromise(name) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (Math.random() > 0.4) {
        resolve(`${name} success`);
      } else {
        reject(`${name} fail`);
      }
    }, Math.random() * 1000);
  });
}

// 模拟:开发者需要提供一个返回 Promise 的函数
let tasks = [0, 1, 2, 3, 4, 5, 6].map((item) => {
  return () => getPromise(item);
});

// 使用 tasks.promise 
runAll(tasks, { maxConcurrent: 3, retry: 2 })
  .then((values) => {
    console.log('run done with succedd', values);
  })
  .catch((values) => {
    console.log('run done with fail', values);
  });

  • runAll 返回 Promise,相当于 Promise.all
  • tasks 入参是一个返回 Promise 的函数数组
  • maxConcurrent 代表并发数, retry 是当某个具体的 Promise 失败后会被重试的次数

逻辑细节

假设开发者提供了 20 个需要并发处理的任务,并且设置并发数为 5,重试次数为 3

整体流程

  • 函数内部会并发执行 5 个 任务
  • 当其中任意一个任务完成,则加入一个新的任务,以保证可以始终以开发者设置的最大并发执行任务,加快效率(相比简单的分批并发效率更高)

某个任务流程

  • 重试次数是指某个任务失败,单个任务被重试的次数。如果在小于 retry 次数内 Promise resolved,那么代表 整体任务成功,否则失败

Keywords

concurrent

FAQs

Package last updated on 25 Feb 2021

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts