Search code examples
javascriptgoogle-chromegoogle-chrome-extensiones6-promise

Returning a promise from a function that gets a response from the background JS of chrome extension


So after the CORB issue of chrome extension i migrated the api calls to background script and used callback from the background script to send response of a JSON.

So I have a doubt regarding the response i receive from callback i want it to return it.

async function request (path, apiToken, options) {
  chrome.runtime.sendMessage({type: "request", path:path, apiToken:apiToken, options:options}, (all) => {
    return Promise.resolve(all.json )
  })
}

I call request => it goes to background => background return the response => then the request function should return a promise. I'm stuck on the last step as im unable to return it from inside the callback,


Solution

  • Return new Promise, resolve it inside your sendMessage callback

    async function request (path, apiToken, options) {
      return new Promise(function(resolve, reject) {
          chrome.runtime.sendMessage({type: "request", path:path, apiToken:apiToken, options:options}, (all) => {
            resolve(all.json)
          })
    }