首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >循环通过chrome.bookmarks.getChildren数组时的JS Promise

循环通过chrome.bookmarks.getChildren数组时的JS Promise
EN

Stack Overflow用户
提问于 2018-11-07 12:46:50
回答 1查看 198关注 0票数 0

我正在开发一个google chrome扩展,我必须循环遍历节点(文件夹),以检查每个文件夹中有多少项。我正在向函数getBookmarksCount(ID)提供一个项目ID。我在从main函数获取结果时遇到了问题,console.log()在日志记录时返回正确的值。

下面是我的代码:

代码语言:javascript
复制
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

这是我更新后的工作版本,没有承诺。setTimeout()是一个肮脏的黑客,但它是有效的。有什么建议可以改进这个功能吗?

代码语言:javascript
复制
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>

EN

回答 1

Stack Overflow用户

发布于 2018-11-07 12:58:34

正如Bravo在评论中指出的那样,你并不是真的在等待你的代码执行。不过,你们已经很接近了!

代码语言:javascript
复制
const getBookmarksCount = (bmkNode) => {
   return new Promise ((resolve) => {
      let nodes = []
      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))
      })
   })
}
getBookmarksCount(123).then(size => {
    console.log(size)
})

请注意第二行上的return new Promise,它与您提供的代码片段有一个关键的区别。通过这样做,您可以等待在这里“返回”,直到您实际完成异步工作并调用resolve。然后,为了获得返回值,您将在调用getBookmarksCount时执行与所使用的相同的.then语法。

希望这会有帮助,当然,也能起作用!

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53183698

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档