I am running into an asynchronous JavaScript problem, having trouble saving a value received in a callback method as an object literal. I am making a Chrome Extension and using the chrome.cookies.getAll
method and am able to get the cookies and read them in the callback, but I am not able to save the value to the object. I am still getting the hang of objects and asynchronous JavaScript and could really use some help.
Here's the code
var app = {
init: function() {
this.activeCookie = {
'sid': null
};
this.setupSession();
// shows null
console.log('session in object : ');
console.log(this.activeCookie['sid']);
},
setupSession: function() {
var that = this;
function setCookiesAsync(that, cookie) {
console.log(cookie);
for(var i=0; i<cookie.length; ++i) {
if(cookie[i]['name'] === 'sid') {
that.activeCookie['sid'] = cookie[i]['value'];
// shows a token
console.log('session in callback : ');
console.log(that.activeCookie['sid']);
}
}
}
chrome.cookies.getAll({
'url': ST.BaseUrl
}, function (cookie) {
setCookiesAsync(that, cookie);
});
}
};
Since the callback executes after
console.log('session in object : ');
console.log(this.activeCookie['sid']);
this.activeCookie['sid']
is null
.
I am wondering how I can save the value to the object so the asynchronous method saves it to the object and the subsequent lines of code execute after setupSession()
is complete.