以前曾问过很多类似的问题,但我相信这是不同的。请仔细阅读以了解情况。
我知道chrome API是异步的。
所以,我正在做的是为某些网站提取cookie:
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.
});
变量 aE 是 undefined 。
我希望有一个简单的实现,可以正确解决这个问题。
... <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>...
输出:
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...>
所以打印4次
现在这是问题所在,它应该只打印一次,但是要打印4次。
正如trincot所建议的那样(感谢男人):
for (let i = 0; i < myUrl.length ; i++) {
outLine[myUrl[i]] = {};
chrome.cookies.getAll({domain: myUrl[i]}, function(cookie) {
var templar = {};