Created
June 27, 2017 11:14
-
-
Save Kamisama666/8c6f34d532c7528114a7549b27fdecde to your computer and use it in GitHub Desktop.
Using promises and reactive programming (RxJs) to implement asynchronous pagination
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
const Rx = require('rx'); | |
getPages(5, 1) | |
.then(reduceToPromise) | |
.then(console.log) | |
function getPages(perPage, page) { | |
return new Promise(function(resolve, reject) { | |
resolve(getAllPages(perPage, page)); | |
}); | |
} | |
function getAllPages(perPage, page) { | |
return Rx.Observable.fromPromise(getPage(perPage, page)) | |
.flatMap((data) => { | |
const items = Rx.Observable.fromArray(data.Data); | |
const next = data.Data.length === perPage ? // whatever condition works | |
getAllPages(perPage, page + 1) : | |
Rx.Observable.empty(); | |
return Rx.Observable.concat( | |
items, | |
next | |
); | |
}); | |
} | |
function getPage(perPage, page) { | |
const content = page < 3 ? [1, 2, 3, 4, 5] : []; | |
return Promise.resolve({ | |
Data: content | |
}); | |
} | |
// Accumulates the results and return them as a promise so you can chain after it | |
function reduceToPromise(observable) { | |
function accumulate(acc, item) { | |
acc.push(item); | |
return acc; | |
} | |
return observable.reduce(accumulate, []).toPromise(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment