Skip to content

Instantly share code, notes, and snippets.

@zachsa
Last active September 23, 2019 06:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zachsa/3ebe174a43cc24adfb3d50d890c03d13 to your computer and use it in GitHub Desktop.
Save zachsa/3ebe174a43cc24adfb3d50d890c03d13 to your computer and use it in GitHub Desktop.
Using graphql/dataloader as a reference, this is an experiment WRT how to implement code that does the same thing, with the same API
function DataLoader (_batchLoadingFn) {
this._timer
this._keys = []
this._batchLoadingFn = _batchLoadingFn
}
DataLoader.prototype.load = function(key) {
clearTimeout(this._timer)
const promisedValue = new Promise ( resolve => this._keys.push({key, resolve}) )
this._timer = setTimeout(() => {
this._batchLoadingFn(this._keys.map(k => k.key))
.then(values => {
this._keys.forEach(({resolve}, i) => {
resolve(values[i])
})
this._keys = []
})
}, 0)
return promisedValue
}
const batchLoadingFunction = keys => new Promise( resolve => resolve(keys.map(k => k * 2)) )
const loader = new DataLoader(batchLoadingFunction)
loader.load(1).then(result => console.log('1', result))
loader.load(2).then(result => console.log('2', result))
setTimeout(() => {
loader.load(3).then(result => console.log('3', result))
loader.load(4).then(result => console.log('4', result))
}, 2000)
@zachsa
Copy link
Author

zachsa commented Sep 23, 2019

  • Push a promise to _keys
  • Promises in the _key array will resolve items in the result array
  • Return the promise pushed to _keys, which corresponds to the load() function call for this key
  • The timeout will only NOT be cleared for the last time this function is called. Therefore _batchLoadingFn will only be called once

For testing sake, the DataLoader is initialized with a batching function that will just double the key per result.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment