Skip to content

Instantly share code, notes, and snippets.

@Kamisama666
Created June 27, 2017 11:14
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 Kamisama666/8c6f34d532c7528114a7549b27fdecde to your computer and use it in GitHub Desktop.
Save Kamisama666/8c6f34d532c7528114a7549b27fdecde to your computer and use it in GitHub Desktop.
Using promises and reactive programming (RxJs) to implement asynchronous pagination
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