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)