Scope of a callback function
I want to implement a function which performs ajax requests (response is json) until there will be no "next" property in response. After that i need to perform some callback function. What is the be开发者_运维知识库st way for this? My code below doesn't work because of the wrong callback's scope, and i cannot imagine how to pass it correctly.
_requestPhotos = function(url, callback) { getYFContent(url, function(data) { // some actions if (!!data.next) { _requestPhotos(data.next, callback); } else { callback(smth); } }); };
There are no obvious errors from the script you've posted. For example, an equivalent test could look like this:
alertResult = function(text) {
console.log("Result is: " + text);
}
doRecursive = function(data, callback) {
if(!!data.next) {
doRecursive(data.next, callback);
} else {
callback(data.value);
}
}
var d = { value: 1, next: { value: 2, next: { value: 3 }}};
doRecursive(d, alertResult);
The log result is "Result is: 3"
, which is what you'd expect.
The error is elsewhere. How are you calling this the first time, what is the callback you're passing to it (and how is it defined) and what exactly does getYFContent do?
精彩评论