I'm developing a google chrome extension and I have to loop trough the nodes (folders) to check how many items I have within each folder. I'm suppling an item ID to the function getBookmarksCount(ID)
. I'm having an issue to get a result from the main function the console.log()
returns correct value at the point of logging.
Here is my code:
const getBookmarksCount = (bmkNode) => {
let nodes = []
let result = 0
new Promise ((resolve, reject) => {
chrome.bookmarks.getChildren(bmkNode, (bmkChildren) => {
_.each(bmkChildren, (item) => {
// Check if the item is a bookmark link
if (!(item.url === undefined || item.url === null)) {
nodes.push(item.title)
}
})
resolve(_.size(nodes))
})
}).then((size) => {
console.log(size) //The correct number of items is listed here eg. 6
result = size
})
return result
}
//I'm suppling a parent folder ID the function should return number of children
getBookmarksCount(123) // eg. 6 -> at the moment returns 0
Here is my updated working version without Promise. setTimeout()
is a dirty hack but works. Any suggestions how I can improve this function?
const getBookmarksCount = (bmkNode) => {
let nodes = []
const getChildrenCount = (bmkNode) => {
chrome.bookmarks.getChildren(bmkNode, (bmkChildren) => {
_.each(bmkChildren, (item) => {
// if is bookmark otherwise loop trough subfolder
(!(item.url === undefined || item.url === null)) ? nodes.push(item.title): getChildrenCount(item.id)
})
})
setTimeout(() => {
$(`#counter_${bmkNode}`).html(_.size(nodes))
}, 50)
}
getChildrenCount(bmkNode)
}
// HTML Template
<label class="label label-primary" id="counter_${item.id}">0</label>