1

这个函数从数据库中获取一个问题,并且应该返回它。该数据库是一个 Parse 对象(https://www.parse.com/docs/js_guide)。如代码中的注释所示,该问题可以从 db 调用的成功函数内部访问,但不能从外部访问,并且简单地将 return 语句放在成功块内也不起作用。代码如下。有什么建议么?

function getQuest(){

    var Question = Parse.Object.extend("Question");
    var query = new Parse.Query("Question");
    var questlist = [];
    var newquestion;
    //get list of questions if chosen track is python or java. track is set globally

    if (track == "python")
    {

        query.equalTo("track", "xstsysysus7");

    } else if (track == "java"){

        query.equalTo("track", "XAWqBgxFAP");

    }

    query.find({

        success: function(questions){
        // return list of questions
            var i = Math.floor(Math.random()*10);
            newquestion = questions[i].get('question');
             console.log(newquestion); // works here

    },

        error: function(error){
            console.log(error.message);
        }


    });

    console.log(newquestion); //returns undefined here
    return newquestion;

}
4

2 回答 2

7

你不能像这样从回调方法返回,这是一个异步问题,你应该使用回调方法从方法中取出你的变量

function getQuest(callback){

var Question = Parse.Object.extend("Question");
var query = new Parse.Query("Question");
var questlist = [];
var newquestion;
//get list of questions if chosen track is python or java. track is set globally

if (track == "python")
{

    query.equalTo("track", "xstsysysus7");

} else if (track == "java"){

    query.equalTo("track", "XAWqBgxFAP");

}

query.find({

    success: function(questions){
    // return list of questions
        var i = Math.floor(Math.random()*10);
        newquestion = questions[i].get('question');
        //call the callback method here and pass your variable as a param
        if(callback != null && callback != undefined){
              callback(newquestion);
        }


},

    error: function(error){
        console.log(error.message);
    }


});

}

现在您可以像这样调用您的 getQuest 方法,而不是使用 var newQ = getQuest()

getQuest(function(newQuestion){
   // do your stuff with newQuestion 
})
于 2013-01-22T06:24:18.780 回答
0

回调(成功和错误)是异步的。在您的函数返回之前,它们可能尚未执行。

于 2013-01-22T06:20:32.240 回答