I am making a Chrome Extension and i have some problems
I want to make a fetch() to Anilist.co and to avoid problems, i want to use await but i have a syntax error :
https://i.sstatic.net/Oqurb.png
Here is the code :
async function getAnimeProgress(animeId) {
var result;
chrome.storage.local.get('access_token', function (items) {
var query = `
query ($id: Int, $page: Int) {
Page (page: $page) {
media (id: $id) {
id
mediaListEntry {
status
progress
}
}
}
}
`;
var variables = {
id: animeId,
page: 1
};
var url = 'https://graphql.anilist.co',
options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer ' + items['access_token'],
},
body: JSON.stringify({
query: query,
variables: variables
})
};
function handleResponse(response) {
console.log('handleResponse exec !');
result = response;
};
function handleError(e) {
console.error(e);
};
await fetch(url, options).then(handleResponse).catch(handleError);
});
return result;
}
I've come a long way since I asked this question. But so did Chrome and the web platform.
To wrap it up, the error here is that the callback in the chrome.storage.local.get
arguments is not async but contains an await
statement, therefore failing to pass syntax checks.
However, you may never need this question anymore because since then, error messages got way clearer (thanks Chrome).
For example, this code snippet now correctly reports Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules
function waitForSomething() {
// a second passing!
return new Promise((resolve) => { setTimeout(resolve, 1000); });
}
function myFunctionContainsAwaitStatementsOhNo() {
await waitForSomething();
}
myFunctionContainsAwaitStatementsOhNo();