所以我遇到了一个问题,即使在经过数小时的试验和错误以及本网站上的多个查询后,我也无法弄清楚自己。
我基本上是在尝试使用Chrome中打开的所有标签的标题填充数组,但请亲自看看:
var children = [];
function updateList(){
chrome.tabs.query({}, function(tabs){
for( i = 0; i < tabs.length; i++){
children.push(tabs[i].title);
}
})
children.push("test")
}
console.log(children);
console.log(children.length);
updateList();
console.log(children);
console.log(children.length);
我的问题是我在tab查询中推送()的数组条目实际上并没有像它们是数组条目一样处理。当我检查阵列时它们出现在控制台中,并且它们根据Chrome确实改变了长度,但是当我记录阵列的长度时,它们不计算在内。我也不能通过以下方式访问它们:
children[2]
我不知道造成这种情况的原因,但我希望有人可以告诉我这是什么!
修改 好的,所以我出于某种原因没有尝试在Chrome控制台中手动检查阵列的长度,但我现在已经这样做了。长度是正确的,因此查询似乎需要太长时间才能生效。现在的问题是:如何强制我的程序等待查询结束?
答案 0 :(得分:0)
chrome.tabs.query是异步的,这就是它需要回调的原因。要确保完成query
回调,请将您自己的回复添加到updateList
,如下所示:
var children = [];
function updateList(callback){
chrome.tabs.query({}, function(tabs){
for( i = 0; i < tabs.length; i++){
children.push(tabs[i].title);
}
children.push("test")
if (callback) {
console.log('calling updateList callback');
callback();
}
})
}
console.log(children);
console.log(children.length);
console.log('calling updateList')
updateList(function() {
console.log('in updateList callback');
console.log(children);
console.log(children.length);
});
console.log('called updateList');