1.0.2 • Published 2 years ago

yaspr v1.0.2

Weekly downloads
-
License
MIT
Repository
-
Last release
2 years ago

YASPR (Yet Another Sequential Promise Resolver)

Is Promise.all causing failures when you need to make 100s of asynchronous network calls? Do you get random file errors when writing multiple files at the same time? Do you need your async methods to be called in a specific order?

Node's Promise.all method will run all of your async methods in parallel which can cause network or file system errors. The method also prevents you from guaranteeing what order the functions are called. YASPR aims to solve these issues by

Install

npm install yaspr

Use

TypeScript

import { sequentialPromises } from "yaspr";

interface Params {
  name: string;
  timeout: number;
}

// Tracks the number of times the function was called
let count = 0;

// Async function that will will wait the designated timeout, print stuff, and return the number of times this function was called
async function someAsyncFunction(params: Params) {
  return await new Promise<number>(resolve => {
    setTimeout(() => {
      count += 1;
      console.log(`Name: ${params.name}, Timeout: ${params.timeout}`);
      resolve(count);
    }, params.timeout);
  });
}

async function run() {
  // Promise.all will resolve the shortest timeouts first.
  // YASPR will resolve in the order they are received.
  const params: Array<Params> = [
    { name: "Michael", timeout: 1000 },
    { name: "Jim", timeout: 500 },
    { name: "Pam", timeout: 750 },
    { name: "Dwight", timeout: 501 }
  ];
  console.log("Running using `Promise.all`. Output order based on timeout");
  console.log(await Promise.all(params.map(someAsyncFunction)));
  count = 0;
  console.log("Running promises sequentially");
  console.log(await sequentialPromises(params, someAsyncFunction));
}

(async () => await run())();

Develop

Get

git clone https://MikeWestbrook@dev.azure.com/MikeWestbrook/MikesNodeModules/_git/yaspr

Build

npm run build

Watch

npm run watch

Run Sample

Runs a simple example. npm run sample