SQL 데이터베이스에서 데이터를 가져 와서 JS 래퍼를 작성하려고합니다. 다음 함수를 사용하여 스크립트를 호출하고 준비가 완료되면 DB에서 정보를 사용합니다.할당 후 Ajax 지정 변수에 액세스 할 수 없습니다.
var User = function() {
this.email = null;
//Async call to get user values
this.current(function(response) {
this.email = response.email;
//The value is assigned/usable at this point
});
};
User.prototype.current = function(callback) {
$.post("php/db_functions.php", {object: "CurrentUser"}).done(function(result) {
callback(JSON.parse(result)[0]);
});
};.
모든 것이 잘 작동하는 것 같다,하지만 난 그것을 만든 후 객체에서 값에 액세스하려고하면, 그것과 같이, 정의되지 않은 반환
var me = new User();
//And then, way after the async call and when me.email should be defined
me.email //Returns undefined
왜 내가 그것을 사용할 수 있습니다 콜백에서,하지만 이후에?
'$ .post()'가 ** 비동기 **이기 때문에. – Pointy
비동기라는 것은 자체적으로 도움이되지 않습니다. 내 문제는 상황이 아니라 타이밍 때문이었습니다. – colonelsanders
좋습니다. 사과드립니다. 이것은 매우 일반적인 오해이며 '새로운 User()'호출이 어디에서 발생했는지 분명하지 않았습니다. – Pointy