batchasync.js/README.md

75 lines
1.3 KiB
Markdown
Raw Permalink Normal View History

2019-06-13 23:44:43 +00:00
# [batchasync.js](https://git.coolaj86.com/coolaj86/batchasync.js)
2019-06-13 23:04:48 +00:00
2019-06-13 23:47:27 +00:00
Like calling `map()` and resolving with `Promise.all()`,
but handling a bounded number of items at any given time.
2019-06-13 23:44:43 +00:00
2019-06-13 23:51:53 +00:00
Want to read about it?
- [Batching async requests in < 50 lines of VanillaJS](https://coolaj86.com/articles/batching-async-requests-50-lines-of-vanilla-js/)
# Install
2019-06-13 23:44:43 +00:00
```bash
npm install --save batchasync
```
2019-06-13 23:51:53 +00:00
# Usage
2019-06-13 23:44:43 +00:00
```js
// Browsers
var batchAsync = window.batchAsync;
```
```js
// Node
var batchAsync = require('batchasync').batchAsync;
```
```js
var batchSize = 4;
var things = ['apples', 'bananas', 'pears'];
function doStuff() {
// ... go fetch things
}
batchAsync(batchSize, things, doStuff).then(function(results) {
// all results, in order, just like Promise.all()
console.log(results[0]);
});
```
2019-06-14 16:52:27 +00:00
## A note on `undefined`
2019-06-13 23:51:53 +00:00
Returning `undefined` will cause an exception to be thrown,
and the Promise to be rejected.
This is on purpose - because `undefined` is indistinguishable from a skipped Promise.
2019-06-13 23:44:43 +00:00
2019-06-13 23:51:53 +00:00
Return `null` instead.
2019-06-13 23:44:43 +00:00
**Example (bad)**:
```js
function doStuff(thing) {
// Oops! forgot to return
request('https://searchallthe.pictures/api/' + thing);
}
```
**Example (good)**:
```js
function doStuff(thing) {
return request('https://searchallthe.pictures/api/' + thing);
}
```
**Example (good)**:
```js
function doStuff(thing) {
return null;
}
```