I've trying to learn cursor-based pagination with Slack's API. My goal is to return an array of all messages using the channel.history method.
I have a javascript recursive fetch function, but I can't seem to get the local variable "final" to return properly.
The part where it logs "Pagination results successful" is logging and returning the array as expected with a length of 204.
When "final" is called upon outside of that scope, the length is 0.
I've tried experimenting with where I return the variable final, but can't seem to get it working. I think it has to do with not using a callback function, but I wasn't sure where to implement that.
Here's what I have (with my Slack token removed).
function paginate() {
let final = [];
let selectChannel = function(ts) {
fetch('https://slack.com/api/channels.history?token=MY_TOKEN&channel=C6W9FH2S0&latest=' + ts)
.then(response => response.json())
.then(responseData => {
let messages = responseData.messages;
if (!responseData.has_more) {
final.push.apply(final, messages);
console.log('Pagination results successfull, 204 items in the array!', final);
return final;
} else {
final.push.apply(final, messages);
selectChannel(messages[messages.length - 1].ts);
}
return final;
})
.catch(error => {
console.log('Error fetching and parsing data', error);
});
}
selectChannel(new Date());
// Returning as 0, when I am expecting 204
console.log("Final Output", final.length);
return final;
}
var x = paginate();
// By extention, this is returning as 0, when I am expecting 204 as well
console.log("Output", x.length);