Last active
June 7, 2016 13:34
Pagination with the changes feed
This file contains hidden or 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
<html> | |
<body> | |
<pre id="display"></pre> | |
<script src="//cdn.jsdelivr.net/pouchdb/latest/pouchdb.min.js"></script> | |
<script src="index.js"></script> | |
</body> | |
</html> |
This file contains hidden or 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
// Destroy the database before doing anything, because I want | |
// you to see the same thing if you reload. | |
// Ignore the man behind the curtain! | |
new PouchDB('sample').destroy().then(function () { | |
return new PouchDB('sample'); | |
}).then(function (db) { | |
function log(str) { | |
var display = document.getElementById('display'); | |
display.innerHTML = display.innerHTML || ''; | |
display.innerHTML += '\n' + str; | |
} | |
// | |
// IMPORTANT CODE STARTS HERE | |
// | |
function makeManyChanges() { | |
var tasks = []; | |
function createDoc(i) { | |
return db.put({_id: 'doc_' + (++i)}) | |
} | |
for (var i = 0; i < 50; i++) { | |
tasks.push(createDoc(i)); | |
} | |
return Promise.all(tasks); | |
} | |
var pageSize = 10; | |
var lastSeq = 0; | |
function fetchNextPage() { | |
return db.changes({ | |
since: lastSeq, | |
limit: pageSize | |
}).then(function (changes) { | |
log('\nFound the following changes:'); | |
changes.results.forEach(function (change) { | |
log(JSON.stringify(change)); | |
}); | |
if (changes.results.length < pageSize) { | |
log('\nAll done!'); | |
} else { | |
lastSeq = changes.results[changes.results.length - 1].seq; | |
return fetchNextPage(); | |
} | |
}); | |
} | |
makeManyChanges().then(function () { | |
return fetchNextPage(); | |
}).catch(function (err) { | |
// handle errors | |
log(err); | |
}) | |
// | |
// IMPORTANT CODE ENDS HERE | |
// | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment