变量在成功函数外无法访问

时间:2013-01-22 06:16:32

标签: javascript jquery

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

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;

}

2 个答案:

答案 0 :(得分: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 
})

答案 1 :(得分:0)

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