2016-02-23 34 views
0

我正在使用react.JS並在視圖中使用ajax請求來代替流量。React.JS的超級響應範圍問題

該響應完美地工作,問題是我無法訪問end函數外的resp體。

這裏是我的代碼 -

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

第一控制檯日誌學生表示我,我需要爲我的視圖中的數據。 學生的第二個控制檯日誌顯示爲空(來自第一個變量)。這絕對是一個範圍問題,我想知道如何解決這個訪問功能外的resp.body?

回答

1

這不是一個範圍問題,它是一個異步(時間)問題。

console.log將在請求回調之前執行,這兩種主要方式將使用回調或promises

回調:

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); 
}); 

承諾:

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); 
    }); 
+0

忘記上這 - 感謝的人發表評論! – CodeFromthe510