I would like to hand over the variable eventurl into the function fetchData, however this seems not to work and I do not know what the issue is. Would really appreciate if someone could help me.
async function fetchData(eventurl) {
const res=await fetch (eventurl);
const record=await res.json();
stock = record.groups[0].sections
document.getElementById("stock").innerHTML = JSON.stringify(stock);
}
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function
(tabs) {
var url = tabs[0].url;
const pid = url.split("/");
const eventpid = pid[5];
const eventurl = "https://availability.ticketmaster.eu/api/v2/TM_CH/availability/" eventpid "?subChannelId=1";
document.getElementById("link").innerHTML = eventurl;
document.getElementById("event").innerHTML = eventpid;
})
fetchData();
CodePudding user response:
Your call to the function fetchData()
is empty. You get a value for eventurl
in the call to chrome.tabs.query
's function, but fetchData is outside, so you can't give it eventurl. If chrome.tabs.query
's function is synchronous, you could define let eventurl
above it, set eventurl
as you are doing, then call fetchData(eventurl)
afterwards.
But since it looks like a callback that might run asynchronously, you could move fetchData(eventurl)
inside chrome.tabs.query
's function.
CodePudding user response:
Your variable const eventurl
only exists inside the anynomous function block. So when you call your function fetchData()
it doesn't know about variables from another block.
In your case, define the variable outside the function in order to use it
async function fetchData(eventurl) {
const res=await fetch (eventurl);
const record=await res.json();
stock = record.groups[0].sections
document.getElementById("stock").innerHTML = JSON.stringify(stock);
}
let eventurl = '';
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function
(tabs) {
var url = tabs[0].url;
const pid = url.split("/");
const eventpid = pid[5];
eventurl = "https://availability.ticketmaster.eu/api/v2/TM_CH/availability/" eventpid "?subChannelId=1";
document.getElementById("link").innerHTML = eventurl;
document.getElementById("event").innerHTML = eventpid;
})
fetchData(eventurl);