简体   繁体   English

React.JS的超级代理响应范围问题

[英]Superagent Response Scope Issue with React.JS

I'm using react.JS and have an ajax request in the view en lieu of flux. 我正在使用react.JS并在代替通量的视图中有一个ajax请求。

The response works perfectly, the problem is I can't access the resp body outside of the end function. 响应工作正常,问题是我无法在end函数之外访问resp主体。

here is my code- 这是我的代码-

    var student= null;
    request
                .get(APIConfig.PATH.TEACHER+"class/"+classid+"/student/"+thing.id)
                .end(function(err,resp){
                    student= resp.body;
                    console.log(student);
                });
    console.log(thing);
    console.log(student); 

the first console log for student shows me the data i need for my view. 学生的第一个控制台日志显示了我查看所需的数据。 the second console log for student shows null (from the first variable). 学生的第二个控制台日志显示为空(来自第一个变量)。 this is definitely a scope issue, i was wondering how to get around this to access resp.body outside the function? 这绝对是一个范围问题,我想知道如何解决这个问题以在功能之外访问resp.body?

It's not a scope issue, it is an async (timing) issue. 这不是范围问题,而是异步(定时)问题。

The console.log will be executed before the callback of the request, the two main ways to do this will be with either callbacks or promises . console.log将在请求回调之前执行,执行此操作的两种主要方法是使用callbacks或promises

Callback: 打回来:

var getStudent = function(callback){
    request
        .get(APIConfig.PATH.TEACHER+"class/"+classid+"/student/"+thing.id)
        .end(function(err,resp){
            callback(resp.body);
        });
});

getStudent(function(student){
    console.log(student);
});

Promise: 诺言:

var getStudent = function(){
    return new Promise(function(resolve, reject){
        request
            .get(APIConfig.PATH.TEACHER+"class/"+classid+"/student/"+thing.id)
            .end(function(err,resp){
                resolve(resp.body);
            });
    });
});

getStudent()
    .then(function(student){
        console.log(student);
    });

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

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