Last active
September 23, 2019 06:15
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For testing sake, the DataLoader is initialized with a batching function that will just double the key per result.