0
var r=[]
chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
    chrome.tabs.sendMessage(tabs[0].id, {type: "getRes"}, function (response) {
        console.log(response)
        r = response
    });
});
console.log(r)

I am making a chrome extension which I need to fetch the response (response is an array) from above for later use (e.g. to pass it to an AJAX call to the backend in my case). I was able to get the response I wanted inside the nested callback functions. However, If I would like to store that response to variable r, due to the nature of asynchronous calls/callback functions in Javascript, I got an empty array r (console shows an empty array outside the function).

After reading on async/wait with shallow understanding, I added async/await to my functions as below and it still didn't work (i.e. console.log(r) outside the function still shows an empty array). What did I do wrong? I thought JS would await the response then run console.log(r). Any help would be greatly appreciated! Apologize in advance if this is a newbie JS question.

var r = [];

(async () => {
    await chrome.tabs.query({active: true, currentWindow: true}, async function (tabs) {
        await chrome.tabs.sendMessage(tabs[0].id, {type: "getRes"}, async function (response) {
            r = await response
            console.log(r)

        });
    })
})()

console.log(r)
codeedoc
  • 454
  • 2
  • 7
  • 16

1 Answers1

0

In the first snippet you should use the asynchronous response inside the innermost callback, more info in Why is my variable unaltered after I modify it inside of a function?

The second snippet is entirely incorrect because this is not how async/await syntax is used and the chrome API methods do not return anything so it's useless to await on them but you can use a WebExtension polyfill:

(async () => {
  const tabs = await browser.tabs.query({active: true, currentWindow: true});
  const response = await browser.tabs.sendMessage(tabs[0].id, {type: 'getRes'});
  console.log(response);
})();
wOxxOm
  • 65,848
  • 11
  • 132
  • 136