Here is a code snippet that I am working with:
var User = {
get: function (options) {
var self = this;
$.ajax({
url: options.url,
success: function (data, response) {
self.nextPageUrl = data.pagination.next_page;
options.success(data, response);
}
});
},
nextPage: function (success) {
this.get({
url: this.nextPageUrl,
success: success
});
}
}
User.get({
url: 'https://cache.getchute.com/v2/albums/aus6kwrg/assets',
success: function (data, response) {
// Through `data.pagination.next_page` I can get the next page URL.
}
});
User.nextPage({
success: function (data, response) {
// Here I want to make a similar request using the next_page based on the previous one.
}
});
The Issue at Hand
Essentially, my problem arises from trying to execute the nextPage()
function after the initial request (User.get()
) has been made. Due to the asynchronous nature of the functions, the this.nextPageUrl
property remains undefined in the nextPage()
method.
So, my question is: Is there a way to maintain the current syntax flow while addressing this issue? Or is it impossible?
And no, making a synchronous request is not an option for me.
Possible Solution
One possible approach could involve implementing an event system: upon making the initial request and calling .nextPage()
, we could listen for an event to be emitted for a certain duration, expecting the this.nextPageUrl
property to be available within that event-based context.
What are your thoughts on this proposed solution?
DISCLAIMER: The value of next_page
is processed by the server before being sent to the client. Using an increment/decrement operation is not an option for me.
If you would like to explore this issue further, feel free to check out the jsFiddle here.