简体   繁体   English

回调函数的范围

[英]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. 我想实现一个执行ajax请求(响应为json)直到没有响应的“ next”属性的函数。 After that i need to perform some callback function. 之后,我需要执行一些回调函数。 What is the best 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. 日志结果是"Result is: 3" ,这是您期望的结果。

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? 您第一次调用此方法是什么,您要传递给它的回调是什么(以及如何定义),以及getYFContent的作用是什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM