Many similar questions have been asked before but I am sure this is different.Please read the whole of it to understand the situation.
I know the chrome API's are asynchronous.
So, what I am doing is fetching cookies for some websites like this :
var myUrl = ["mywebsite.com","mywebsite2.com","mywebsite3.com","mywebsite4.com"];
var outLine = {};
var aE;
for (var i = 0; i < myUrl.length ; i++) {
outLine[myUrl[i]] = {};
chrome.cookies.getAll({domain: myUrl[i]}, function(cookie) {
var templar = {};
var str = cookie[0]['domain'];
var domain = str.split('.');
var length = domain.length;
var url = domain[length-2]+"."+domain[length-1];
var cLength = cookie.length;
console.log(cLength);
for(var j=0; j < cLength; j++){
templar[j] = JSON.stringify(cookie[i]);
}
outLine[url]=JSON.stringify(templar);
// This should have been outside the loop but
// as it is asynchronous so I put it inside so eventually it
// will have all the cookies as desired
// actually this was the first problem
aE = JSON.stringify(outLine);
});
}
chrome.storage.local.get('uid', function(id){
// Here I want to use the variable aE
//But am unable to do so due to asynchronous
// So, it was all good when there wasn't any loop, only one
// chrome API , but here the next chrome API call is dependent
// on previous' value.
});
So , by now you would have understood what the problem would be.
The variable aE is undefined.
I want to have a simple implementation , that solves this problem correctly.
Thanks.
After suggestions from trincot I did some changes like this :
... <snip> ...
outLine[url]=JSON.stringify(templar);
aE = JSON.stringify(outLine);
console.log("Inside Startup : iteration #"+i);
if(i == myUrl.length){
console.log("Complete aE :"+aE);
sendData(aE);
}
...<snip>...
function sendData(aE){
console.log("Inside sendData"+aE);
...<snip>...
The output :
Inside Startup : iteration #4
Complete aE : <...aE...>
Inside sendData<....aE...>
Inside Startup : iteration #4
Complete aE : <...aE...>
Inside sendData<....aE...>
Inside Startup : iteration #4
Complete aE : <...aE...>
Inside sendData<....aE...>
Inside Startup : iteration #4
Complete aE : <...aE...>
Inside sendData<....aE...>
So this prints 4 times
Now this is the problem , it should be printing only once but it is being printed 4 times.
Solution
As suggested by trincot ( It worked thanks man ):
Just changing the var to let ( since var has the scope of the whole function , regardless of block scope but let is limited to the block scope let vs var )
for (let i = 0; i < myUrl.length ; i++) {
outLine[myUrl[i]] = {};
chrome.cookies.getAll({domain: myUrl[i]}, function(cookie) {
var templar = {};