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 parallelparallelLimit
Runs maximum of{limit}
number of tasks in parallelwaterfall
- Run tasks one by one, passing down the result of previous taskseries
- Runs tasks in a series
npm install async-await-control
or if you use yarn
yarn add async-await-control
Run any number of tasks in parallel
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 }
Run tasks one by one, passing down the result of previous task
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
Runs tasks in a 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]]