parse.com中的参数query.find成功回调 [英] Arguments in Parse.com query.find success callback

查看:184
本文介绍了parse.com中的参数query.find成功回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

感谢您的帮助。
我正在使用Phonegap和Javascript进行练习分配。长故事:我需要使用Parse.com来存储关于一些乐高迷你的信息。我现在遇到的问题主要是因为我对Javascript的经验不足。



我正在努力让用户给图形添加标签。用户输入它们,用逗号分隔,然后我拆分字符串。



现在,我需要将尚不存在的标签添加到我的数据库中。为此,我搜索任何具有该描述的标签(使用query.find),然后,如果它存在,我不创建它,我只是修改关系。如果它不存在,我创建它,然后修改关系。



我的问题是:我似乎不能访问标记描述字符串)从query.find的成功回调内。我很确定这是因为范围。除了结果数组,有没有任何适当的方法来访问变量从成功回调?



我当前的代码如下:

  var Figure = Parse.Object.extend(Figure); 
var Tag = Parse.Object.extend(Tag);
var nombre = $('#nombre')。val();
var serie = $('#serie')。val();
var figure = new Figure({Name:nombre,Series:serie});
var tags = $('#tags')。val();
res = tags.split(,); // split the
figure.save()。then(function(){
for(var i = 0; i< res.length; i ++){// for each tag

var query = new Parse.Query(Tag); //创建查询
query.equalTo(Description,res [i]);
query.find执行查询
success:function(results,res [i]){
if(results.length> 0){//如果有结果
var tag = results [0] ; //获取标签
var relation_tag = tag.relation(figures); //获取关系
relation_tag.add(figure); //将figure添加到关系
标签。 save();
}
else {//如果没有结果,则标记不存在
new_tag = new Tag({Description:res [i]
//上面这行:res [i]总是未定义。
var relation_tag = new_tag.relation(figures); //获取关系
relation_tag.add(figure); // add the figure
new_tag.save();
}
},
//查询错误
错误:function(){
alert(ERROR);
}


});

}


},函数(错误){

alert(No se pudo guardar la figura);

});

在成功回调中,res [i]总是未定义的,我认为这是因为范围。

解决方案

这是异步Javascript编程中非常常见的问题。您正在这样做:

  for(var i = 0; i  anAsyncFunction(function(result){//内部函数
doSomethingWith(array [i]);
}
}

问题是在Javascript函数中,通过引用存储外部变量而不是值,这意味着函数从外部范围中查找变量的值,因为代码是异步的,在for循环完成后调用内部函数,此时我们有 i === array.length array [i] === array [array.length] === undefined



避免这种情况,您可以使用立即调用的函数表达式(IIFE,发音为iffy):

  for(var i = 0; i  anAsyncFunction((function(j){// IIFE 
return function innerFunction(result){// inner function
doSomethingWith ); // j而不是i
}
})(i); //传递i的值
}

因为立即调用IIFE,当前值为 i 被传递并存储到 j ,当内部函数执行时,它使用正确的值。 / p>

所以在你的情况下,这应该工作:

  (j){// IIFE 
return function(results){
if(results.length> 0){
var tag = results [0];
var relation_tag = tag.relation(figures);
relation_tag.add(figure);
tag.save();
}
else {//如果没有结果标签不存在
new_tag = new Tag({Description:res [j]}); // j代替i
var relation_tag = new_tag.relation(figures);
relation_tag.add(figure);
new_tag.save();
}
}
})(i)//传递i的价值

如果你愿意,你也可以传递描述本身,而不仅仅是索引到IIFE这样):

  success:(function(description){// IIFE 
return function
if(results.length> 0){
var tag = results [0];
var relation_tag = tag.relation(figures);
relation_tag.add(figure);
tag.save();
}
else {//如果没有结果,标记不存在。
new_tag = new Tag({Description:description}); // description
var relation_tag = new_tag.relation(figures);
relation_tag.add(figure);
new_tag.save();
}
}
})(res [i])// pass description


Thanks for the help in advance. I'm working on an practice assigment using Phonegap and Javascript. Long story short: I need to use Parse.com to store information about some Lego minifigures. The problem I'm having right now is due mostly to my inexperience in Javascript.

I'm working on letting the user add tags to the figures. The user enters them, separated by comma, and I then split the string. That's working OK.

Now, I need to add the tags that don't exist yet to my database. For this, I search for any tags with that description (using query.find) and then, if it exists, I don't create it, I just modify the relationship. If it doesn't exist, I create it and then modify the relationship.

My problem is: I can't seem to be able to access the tag description (the string) from within the success callback of query.find. I'm pretty sure it's because of the scope. Is there any proper way to access variables from withing a success callback, besides the results array?

My current code is as follows:

                var Figure = Parse.Object.extend("Figure");
                var Tag = Parse.Object.extend("Tag");
                var nombre = $('#nombre').val();
                var serie = $('#serie').val();
                var figure = new Figure({"Name":nombre,"Series":serie});
                var tags = $('#tags').val();
                res = tags.split(","); //split the 
                figure.save().then(function() {
                    for (var i = 0; i < res.length; i++) { //for each tag

                        var query = new Parse.Query(Tag); //create the query.
                        query.equalTo("Description", res[i]);
                        query.find( {//execute query                                
                            success: function(results, res[i]) {
                             if (results.length > 0){ //if there are results.
                                var tag = results[0]; //get the tag
                                var relation_tag = tag.relation("figures"); //get the relation
                                relation_tag.add(figure); //add figure to relation
                                tag.save();
                              }
                             else { //if there are no results, the tag does not exist.
                                new_tag = new Tag({"Description":res[i]}); 
                               //ABOVE THIS LINE: res[i] is always undefined.
                                var relation_tag = new_tag.relation("figures"); //get the relation
                                relation_tag.add(figure); //add the figure
                                new_tag.save();
                              }
                            },
                            //error with query
                            error: function() {
                             alert("ERROR");
                            }


                        });     

                    }                                           


                }, function(error) {

                    alert("No se pudo guardar la figura");

                });

In the success callback, res[i] always is undefined, I assume that it's because of the scope.

解决方案

This is a very common problem in async Javascript programming. You are doing something like this:

for (var i = 0; i < array.length; i++) {
    anAsyncFunction(function(result) { // inner function
        doSomethingWith(array[i]);
    }
}

The problem is that in Javascript functions store outer variables by reference and not by value, which means that a function looks up the value of a variable from an outer scope, when it is executed and not when it is defined. Since the code is async the the inner function is called after the for loop completed and at this point we have i === array.length, so array[i] === array[array.length] === undefined.

To avoid this you can use an immediately invoked function expression (IIFE, pronounced "iffy"):

for (var i = 0; i < array.length; i++) {
    anAsyncFunction((function(j) { // IIFE
        return function innerFunction(result) { // inner function
           doSomethingWith(array[j]); // j instead of i
       }
    })(i); // passing "value of i"
}

Because the IIFE is invoked immediately, the current value is of i is passed and stored into j and when the inner function executes it uses the correct value.

So in your case this should work:

success: (function(j) { // IIFE
    return function(results) {
        if (results.length > 0) {
            var tag = results[0];
            var relation_tag = tag.relation("figures");
            relation_tag.add(figure);
            tag.save();
        }
        else { //if there are no results, the tag does not exist.
            new_tag = new Tag({"Description":res[j]}); // j instead of i
             var relation_tag = new_tag.relation("figures");
            relation_tag.add(figure);
            new_tag.save();
        }
    }
})(i) // pass "value of i"

If you prefer, you can also pass the description itself instead of just the index to the IIFE (I think I would do it that way):

success: (function(description) { // IIFE
    return function(results) {
        if (results.length > 0) {
            var tag = results[0];
            var relation_tag = tag.relation("figures");
            relation_tag.add(figure);
            tag.save();
        }
        else { //if there are no results, the tag does not exist.
            new_tag = new Tag({"Description":description}); // description
             var relation_tag = new_tag.relation("figures");
            relation_tag.add(figure);
            new_tag.save();
        }
    }
})(res[i]) // pass description

这篇关于parse.com中的参数query.find成功回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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