简体   繁体   English

JavaScript构建JSON异步和dynamicall

[英]JavaScript building JSON asynchronous and dynamicall

I have some trouble with asynchronous JavaScript. 我在使用异步JavaScript时遇到了一些麻烦。 I call a function within a jQuery AJAX call, and in this function there are probably other asynchronous methods calls. 我在jQuery AJAX调用中调用了一个函数,并且在此函数中可能还有其他异步方法调用。 I stuck in there on the moment. 此刻我呆在那里。

Here I have the code snippet which is called by the jQuery AJAX function: Here I build dynamically a JSON object. 在这里,我有jQuery AJAX函数调用的代码片段:在这里,我动态地构建一个JSON对象。

function getJSONObjektList() {
    //MainJSON
    var jsonObjekt = {};
    jsonObjekt.ObjektId = [];
    jsonObjekt.Selected = [];

    doc = XYZ.GetCurrentDocument();
    //probably also an asynchrounous call
    doc.GetAllObjects(function (objects) {
        for (var i = 0; i < objects.length; i++) {
            var obj = objects[i];
            var id = obj.id;
            var caption = obj.caption;
            var type = obj.type;
            var my = obj.my;
            console.log("[obj:" + obj + " id:" + id + " caption:" + caption + " type:" + type + " my: " + my + "]");

            //liste alle verfuegbaren  Objekte auf 
            jsonObjekt.ObjektId.push(id);

            if (type === "Statusbox") {
                doc.GetObject(id, function () {
                    var statusboxInhalt = this.Data.Rows;
                    //inner JSON object                        
                    var utilJSONObjekt;

                    for (var j = 0; j < statusboxInhalt.length; j++) {
                        // make sure to re-initialize so we don't update the same reference
                        utilJSONObjekt = {};
                        utilJSONObjekt.SelectedObjektId;
                        utilJSONObjekt.SelectedObjektWerte = [];

                        var inhalt = statusboxInhalt[j];
                        console.log("Name: " + inhalt[0].text + " Wert: " + inhalt[2].text);

                        utilJSONObjekt.SelectedObjektId = inhalt[0].text;

                        var valAr = inhalt[2].text.split(",");
                        for (var k = 0; k < valAr.length; k++) {
                            utilJSONObjekt.SelectedObjektWerte.push($.trim(valAr[k]));
                        }
                        jsonObjekt.Selected.push(utilJSONObjekt);
                        //**till here is the jsonObject not null or empty, there are some values in there**
                    }
                });
            }
        }
    });
    //**but on the return statment is the jsonObjekt empty**
    return jsonObjekt;
}

Have someone some tips how can I solve my problem, or how can I make JavaScript best asynchronously working. 告诉别人一些技巧,该如何解决我的问题,或者如何使JavaScript最佳地异步工作。

Yeah, simply use callback pattern: 是的,只需使用回调模式:

function getJSONObjektList(callback) { // <--- note callback
   // asynchronous code starts here...
               for (var k = 0; k < valAr.length; k++) {
                   utilJSONObjekt.SelectedObjektWerte.push($.trim(valAr[k]));
               }
               jsonObjekt.Selected.push(utilJSONObjekt);
               callback(jsonObjekt);
   // ...and ends here
}

and in your code you can use it like that: 在您的代码中,您可以像这样使用它:

getJSONObjektList(function(jsonObjekt) {
    console.log(jsonObjekt);
    // other code
});

EDIT Here's an example of two solutions to the same problem. 编辑这是解决同一问题的两种解决方案的示例。 One with callback pattern and one without it: 一种带有回调模式,另一种没有回调模式:

no callback 没有回调

var add = function(x,y) {
    return x+y;
};
var x = 1;
var sum = add(x, 1);
var sum2 = add(sum, 1);
console.log(sum2);

callback 打回来

var add = function(x,y,callback) {
    callback(x+y);
}
var x = 1;
add(x, 1, function(sum) {
    add(sum, 1, function(sum2) {
        console.log(sum2);
    });
});

Obviously the callback pattern is more messy, but if you are dealing with asynchronous operations then you absolutely need it, for example: 显然,回调模式更加混乱,但是如果您要处理异步操作,则绝对需要它,例如:

var add = function(x, y, callback) {
    // add numbers after 2 seconds
    setTimeout(function() {
        callback(x+y);
    }, 2000);
}
add(1, 2, function(sum) {
    console.log(sum);
    // will produce 3 after 2 seconds
    // you can continue your code here
});

The idea is to pass a function which will be called after the asynchronous operation is done. 这个想法是传递一个函数,该函数将在异步操作完成后被调用。

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

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