diff --git a/README.md b/README.md index 5b7d146..f14464e 100644 --- a/README.md +++ b/README.md @@ -90,7 +90,19 @@ minimal outgoing data requests. #### Batch Function A batch loading function accepts an Array of keys, and returns a Promise which -resolves to an Array of values. There are a few constraints that must be upheld: +resolves to an Array of values or Error instances. The loader itself is provided +as the `this` context. + +```js +async function batchFunction(keys) { + const results = await db.fetchAllKeys(keys) + return keys.map(key => results[key] || new Error(`No result for ${key}`)) +} + +const loader = new DataLoader(batchFunction) +``` + +There are a few constraints this function must uphold: * The Array of values must be the same length as the Array of keys. * Each index in the Array of values must correspond to the same index in the Array of keys. @@ -116,7 +128,7 @@ with the original keys `[ 2, 9, 6, 1 ]`: [ { id: 2, name: 'San Francisco' }, { id: 9, name: 'Chicago' }, - null, + null, // or perhaps `new Error()` { id: 1, name: 'New York' } ] ``` diff --git a/src/__tests__/dataloader.test.js b/src/__tests__/dataloader.test.js index d1284ea..5327a43 100644 --- a/src/__tests__/dataloader.test.js +++ b/src/__tests__/dataloader.test.js @@ -30,6 +30,19 @@ describe('Primary API', () => { expect(value1).toBe(1); }); + it('references the loader as "this" in the batch function', async () => { + let that; + const loader = new DataLoader(async function (keys) { + that = this; + return keys; + }); + + // Trigger the batch function + await loader.load(1); + + expect(that).toBe(loader); + }); + it('supports loading multiple keys in one call', async () => { const identityLoader = new DataLoader(keys => Promise.resolve(keys)); diff --git a/src/index.js b/src/index.js index 44aa9b9..c38c983 100644 --- a/src/index.js +++ b/src/index.js @@ -253,7 +253,8 @@ function dispatchQueueBatch( // Call the provided batchLoadFn for this loader with the loader queue's keys. var batchLoadFn = loader._batchLoadFn; - var batchPromise = batchLoadFn(keys); + // Call with the loader as the `this` context. + var batchPromise = batchLoadFn.call(loader, keys); // Assert the expected response from batchLoadFn if (!batchPromise || typeof batchPromise.then !== 'function') {