npm.io
0.2.1 • Published 8 years ago

async-await-control

Licence
MIT
Version
0.2.1
Deps
1
Size
15 kB
Vulns
0
Weekly
0

Async/await utility functions

This library provides control flow utility functions for async/await. Since async/await returns promises, you can also use it with plain .then and .catch. Includes the following:

  • paralell - Run any number of tasks in parallel
  • parallelLimit Runs maximum of {limit} number of tasks in parallel
  • waterfall - Run tasks one by one, passing down the result of previous task
  • series - Runs tasks in a series

Instalation

npm install async-await-control

or if you use yarn

yarn add async-await-control

Usage

Parallel / Parallel limit

Run any number of tasks in parallel

Parameters
Name Type Description
tasks Iterable|Object A collection of async functions to run. Each async function must return a Promise or a value.
limit Number (Optional) Limit the number of parallel tasks
// tasks can be Array/Iterable/Object
const tasks = {
  first: () => Promise.resolve(1),
  second: () => Promise.resolve(2),
  third: () => Promise.resolve(3)
};

const res = await parallel(tasks, 2);
// { first: 1, second: 2, third: 3 }
Waterfall

Run tasks one by one, passing down the result of previous task

Waterfall
Name Type Description
tasks Iterable An array of async functions to run. Each function should complete with any number of result values. The result values will be passed as arguments, in order, to the next task.

Returns array of results or a single value if only single value is passed in the last iteratee.

const tasks = [
  () => Promise.resolve(1),
  (a) => Promise.resolve([1, 2]), // a = 1
  (a, b) => Promise.resolve([3, 4]), // a = 1, b = 2
];

const res = await waterfall(tasks);
// [4, 5]


const tasks = [
  () => Promise.resolve(1),
  (a) => Promise.resolve([1, 2]), // a = 1
  (a, b) => Promise.resolve(3), // a = 1, b = 2
];

const res = await waterfall(tasks);
// 3
Series

Runs tasks in a series

Series
Name Type Description
tasks Iterable An array of async functions to run. Each function should return a Promise or a value.
const tasks = [
  () => Promise.resolve(1),
  () => Promise.resolve([1, 2]),
  () => Promise.resolve([3, 4]),
];

const res = await waterfall(tasks);
// [1, [1, 2], [3, 4]]

Keywords