成功函数外部无法访问的变量 [英] variable not accessible outside success function

查看:61
本文介绍了成功函数外部无法访问的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

this function gets a question from a database and is supposed to return it. The database is a Parse object(https://www.parse.com/docs/js_guide). As indicated in the comments in the code the question is accessible from within the success function of the db call but not from outside it and simply putting the return statement inside the success block doesn't work either. Code below. Any suggestions?

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;

}

推荐答案

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

You cannot return from the callback method like this, this is an async issue, you should use a callback method to get your variable out from the method

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()

Now you can call your getQuest method just like this instead of using var newQ = getQuest()

getQuest(function(newQuestion){
   // do your stuff with newQuestion 
})

这篇关于成功函数外部无法访问的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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