javascript - What is the best way to approach pagination with Promises? -
my friend , working promises, , making sure getting pages of data before returning our initial call. there more trivial way approach this?
function getdocuments(startindex, result, entries) { startindex = typeof startindex !== 'undefined' ? startindex : 0; result = typeof result !== 'undefined' ? result : {}; entries = typeof entries !== 'undefined' ? entries : []; // build our entries set result parameter for(var in result.items) { try { var id = result.items[i].id; var name = result.items[i].name; var content = result.items[i].content; var entry = { "id": id, "name": name, "content": content }; entries.push(entry); } catch(e) { } } // return promise fulfills promise returns either promise or result. return new promise(function(fulfill, reject) { // fulfill promise , resolve value, pass recursive promise value. fulfill(documentclient.getdocuments({ "startindex": startindex }).then(function(result) { // once our request made, let's check page count. var startindex = result.startindex; var pagesize = result.pagesize; var totalcount = result.totalcount; if (startindex + pagesize <= totalcount) { // if our current position not @ end of pages, return promise our current data , our current entries. return getdocuments(startindex + pagesize, result, entries); } return entries; // otherwise our entries bubble stack , resolved initial fulfill value. })); }); } getdocuments().then(function(d) { console.log(d.length); }); my adjustments:
function getdocuments(startindex, result, entries) { startindex = typeof startindex !== 'undefined' ? startindex : 0; result = typeof result !== 'undefined' ? result : {}; entries = typeof entries !== 'undefined' ? entries : []; // build our entries set result parameter // ... // return promise fulfills promise returns either promise or result. return documentclient.getdocuments({ "startindex": startindex }).then(function(result) { // once our request made, let's check page count. var startindex = result.startindex; var pagesize = result.pagesize; var totalcount = result.totalcount; if (startindex + pagesize <= totalcount) { // if our current position not @ end of pages, return promise our current data , our current entries. return getdocuments(startindex + pagesize, result, entries); } return entries; // otherwise our entries bubble stack , resolved initial fulfill value. }); } getdocuments().then(function(d) { console.log(d.length); });
yes, can chain promises documentclient.getdocuments returns promise.
function getdocuments(startindex, result, entries) { // ... return documentclient.getdocuments({ "startindex": startindex }).then(function(result) { // ... return entries; // otherwise our entries bubble stack , resolved initial fulfill value. }); } getdocuments().then(function(d) { console.log(d.length); });
Comments
Post a Comment