问题
I need to fetch some JSON data from an API and assign the result to a variable. I can see the array of data in the console, but [abc] is always set as a Pending promise.
I've tried to assign [abc] instead of logging [data] or simply returning [data] but it's not working. Ideally, I would also want to stop the execution of the following code until I get the required data but with the code I have, the text gets logged before the data
async function fetchData()
{
let response = await fetch('API');
let data = await response.json();
data = JSON.stringify(data);
data = JSON.parse(data);
return data;
}
let abc = await fetchData()
.then(data => console.log(data));
console.log('This should not be logged if 'abc' does not have the data i need')
(data => console.log(data)) ..>> here the data is the array I need but I have no idea on how to assign on a variable.
I've looked for many solutions on the internet but I couldn't find anything that could help.
EDIT 1:
If I assign: let abc = await fetchData() without the then statement it throws me this error: Uncaught SyntaxError: await is only valid in async function
If I then remove the await keyword it returns Promise without having it resolved.
回答1:
In order for await
keyword to work, it must sit inside a async
function. So you need to wrap your code in a async function first, let's say a main function, then call it. Example:
async function fetchData() {...}
async function main() {
let abc = await fetchData();
console.log(abc);
}
main();
回答2:
it should be like this
async function fetchData(){
let response = await fetch('API');
let data = await response.json();
data = JSON.stringify(data);
data = JSON.parse(data);
return data;
}
let abc = await fetchData(); // here the data will be return.
console.log(abc); // you are using async await then no need of .then().
来源:https://stackoverflow.com/questions/55595847/how-to-save-results-of-a-promise-to-a-variable