如何“递归AJAX回调"在JavaScript中工作? [英] How do "recursive AJAX callbacks" in JavaScript work?

查看:41
本文介绍了如何“递归AJAX回调"在JavaScript中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Github API检索有关我的一个回购协议的数​​据,我遇到了回调函数和递归函数重叠的麻烦(例如在附加了回调的递归函数中)

I am using the Github API to retrieve data about one of my repos and I am running into trouble with callback functions and recursive functions overlapping (as in recursive functions with callbacks attached to them)

这是jsfiddle上的脚本以及以下内容:

(function () {
    'use strict';

    function makeAJAXCall(hash, cb) {
        $.ajaxSetup({
            accept: 'application/vnd.github.raw',
            dataType: 'jsonp'
        });

        $.ajax({
            url: hash,
            success: function (json) {
                //console.info(json);
                // Time for callback to be executed
                if (cb) {
                    cb(json);
                }
            },
            error: function (error) {
                console.error(error);
                // an error happened, check it out.
                throw error;
            }
        });
    }

    function parseBlob(hash) {
        return makeAJAXCall(hash, function (returnedJSON) {  // no loop as only one entry
            console.log(returnedJSON.data);
            return returnedJSON.data.content;
        });
    }

    function walkTree(hash) {
        var tree = 'https://api.github.com/repos/myusername/SVG-Shapes/git/trees/' + hash;
        return makeAJAXCall(tree, function (objectedJSON) {
            var objectList = [], i, entry;
            for (i = 0;  i < objectedJSON.data.tree.length; i += 1) {
                entry = objectedJSON.data.tree[i];
                //console.debug(entry);
                if (entry.type === 'blob') {
                    if (entry.path.slice(-4) === '.svg') {     // we only want the svg images not the ignore file and README etc
                        //console.info(entry.path)
                        objectList.push(parseBlob(entry.url));
                    }
                } else if (entry.type === 'tree') {
                    objectList.push(walkTree(entry.sha));
                }
            }
            if (cb) {
                console.log(objectList);
                cb(objectList);
            }
            return objectList;
        });
    }

    $(document).ready(function () {
        var returnedObjects = walkTree('master', function (objects) {     // master to start at the top and work our way down
            console.info(objects);
        });
    });
}());

返回的JSON是博客(文件)或树(目录).如果是树,则再次调用walkTree函数.我不了解回调在这里的行为以及如何使它(应该)将数据从函数中返回到最底部的最终块中.

The JSON returned is either blog (file) or tree (directory). If it is a tree the walkTree function is called again. I do not understand how the callback will behave here as well as how to get the data it (should) return(s) out of the function and into the final block at the very bottom.

有人可以澄清我应该怎么做吗?

Can someone clarify how I should be doing this?

推荐答案

Ajax调用通常是异步的.这意味着,当您进行ajax调用时,它只会启动ajax调用,并在一段时间后完成.同时,启动ajax调用后的其余代码将一直运行直到完成.

Ajax calls are usually asynchronous. That means that when you make the ajax call, it just initiates the ajax call and it finishes some time later. Meanwhile, the rest of your code after the initiation of the ajax call keeps running until completion.

然后,稍后某个时间,ajax调用完成时,将调用成功函数,并且在您的情况下,成功函数将调用回调函数.重要的是要了解,成功函数在 makeAJAXCall()函数完成之后被调用得多.

Then, sometime later when the ajax call finishes, the success function is called and, in your case, the callback function gets called by the success function. It is important to understand that the success function is called much later after the makeAJAXCall() function has already finished.

因此,您不能从 makeAJAXCall()函数返回ajax数据,因为该函数返回时尚不知道.

Thus, you cannot return the ajax data from the makeAJAXCall() function because it isn't known yet when that function returns.

实际上,可以使用ajax调用的结果的唯一两个位置是:

In fact, the only two places you can use the results of the ajax call are:

  1. 直接在成功处理程序中
  2. 在成功处理程序调用的某些函数中,您认为是回调函数.

因此,从回调函数返回 returnedJSON.data.content; 对您没有好处.那只是回到ajax基础结构的某些内部部分,什么也不做.那个返回值只会掉在地板上而丢失.

So, it is doing you no good to return returnedJSON.data.content; from the callback function. That is just returning into some internal part of the ajax infrastructure and doing nothing. That return value will just be dropped on the floor and lost.

相反,您需要在该回调函数中放任何想要使用 returnedJSON.data.content 的代码(或通过函数调用将其传递给另一个函数).

Instead, you need to put whatever code wants to use returnedJSON.data.content right there in that callback function (or pass it to another function with a function call).

Ajax是异步的.这意味着使用ajax时无法进行常规的顺序编程.相反,您必须进行事件驱动的编程,在这种情况下,事件是在成功完成ajax调用后调用的回调.使用这些ajax结果的所有工作都需要从该成功处理程序或从该处理程序中调用的回调开始.

Ajax is asynchronous. That means you can't do normal sequential programming when using ajax. Instead, you have to do event driven programming where the event in this case is the callback that is called upon a success completion of the ajax call. All work that uses those ajax results needs to commence from that success handler or the callback that is called from it.

这篇关于如何“递归AJAX回调"在JavaScript中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆