Skip to content

Commit 67dbc7a

Browse files
committed
Improve documentation of the expectations of a Batch Function.
Suggested in #66
1 parent eec8bdf commit 67dbc7a

File tree

1 file changed

+39
-1
lines changed

1 file changed

+39
-1
lines changed

README.md

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,9 @@ unique cache. You might create each loader once for your whole application, or
5454
create new instances per request when used within a web-server like [express][]
5555
if different users can see different things. It's up to you.
5656

57+
58+
### Batching
59+
5760
Batching is not an advanced feature, it's DataLoader's primary feature.
5861
Create loaders by providing a batch loading function.
5962

@@ -64,7 +67,7 @@ var userLoader = new DataLoader(keys => myBatchGetUsers(keys));
6467
```
6568

6669
A batch loading function accepts an Array of keys, and returns a Promise which
67-
resolves to an Array of values.
70+
resolves to an Array of values[<sup>*</sup>](#batch-function).
6871

6972
Then load individual values from the loader. DataLoader will coalesce all
7073
individual loads which occur within a single frame of execution (a single tick
@@ -92,6 +95,41 @@ presented to your batch loading function. This allows your application to safely
9295
distribute data fetching requirements throughout your application and maintain
9396
minimal outgoing data requests.
9497

98+
#### Batch Function
99+
100+
A batch loading function accepts an Array of keys, and returns a Promise which
101+
resolves to an Array of values. There are a few constraints that must be upheld:
102+
103+
* The Array of values must be the same length as the Array of keys.
104+
* Each index in the Array of values must correspond to the same index in the Array of keys.
105+
106+
For example, if your batch function was provided the Array of keys: `[ 2, 9, 6, 1 ]`,
107+
and loading from a back-end service returned the values:
108+
109+
```js
110+
{ id: 9, name: 'Chicago' }
111+
{ id: 1, name: 'New York' }
112+
{ id: 2, name: 'San Francisco' }
113+
```
114+
115+
Our back-end service returned results in a different order than we requested, likely
116+
because it was more efficient for it to do so. Also, it omitted a result for key `6`,
117+
which we can interpret as no value existing for that key.
118+
119+
To uphold the constraints of the batch function, it must return an Array of values
120+
the same length as the Array of keys, and re-order them to ensure each index aligns
121+
with the original keys `[ 2, 9, 6, 1 ]`:
122+
123+
```js
124+
[
125+
{ id: 2, name: 'San Francisco' },
126+
{ id: 9, name: 'Chicago' },
127+
null,
128+
{ id: 1, name: 'New York' }
129+
]
130+
```
131+
132+
95133
### Caching
96134

97135
After being loaded once, the resulting value is cached, eliminating

0 commit comments

Comments
 (0)