How do I use promises in a Chrome extension?

前端 未结 2 350
广开言路
广开言路 2020-12-20 07:29

What I am trying to do is create a chrome extension that creates new, nested, bookmark folders, using promises.

The function to do this is chrome.bookmarks.creat

相关标签:
2条回答
  • 2020-12-20 07:46

    Honestly, you should just use the web extension polyfill. Manually promisifying the chrome APIs is a waste of time and error prone.

    If you're absolutely insistent, this is an example of how you'd promisify chrome.bookmarks.create. For other chrome.* APIs, you also have to reject the callback's error argument.

    function createBookmark(bookmark) {
      return new Promise(function(resolve, reject) {
        try {
          chrome.bookmarks.create(bookmark, function (result) {
            if (chrome.runtime.lastError) reject(chrome.runtime.lastError)
            else resolve(result)
          })
        } catch (error) {
          reject(error)
        }
      })
    }
    
    
    createBookmark({})
      .then(function (result) {
         console.log(result)
       }).catch(function (error) {
         console.log(error)
       })

    To create multiple bookmarks, you could then:

    function createBookmarks(bookmarks) {
      return Promise.all(
        bookmarks.map(function (bookmark) {
          return createBookmark(bookmark)
        })
      )
    }
    
    createBookmarks([{}, {}, {}, {}])
      .catch(function (error) {
        console.log(error)
      })

    0 讨论(0)
  • 2020-12-20 08:00

    Take the advantage of the convention that the callback function always be the last argument, I use a simple helper function to promisify the chrome API:

    function toPromise(api) {
      return (...args) => {
        return new Promise((resolve) => {
          api(...args, resolve);
        });
      };
    }
    

    and use it like:

    toPromise(chrome.bookmarks.create)(bookmark).then(...);
    

    In my use case, it just works most of the time.

    0 讨论(0)
提交回复
热议问题