How to save results of a promise to a variable?
Solution 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();
Solution 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().
John
Updated on April 10, 2020Comments
-
John about 4 years
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.
-
John about 5 yearsOh yeah, I forgot to describe this scenario. This was my first attempt and it actually throws me this error: ' Uncaught SyntaxError: await is only valid in async function '
-
amitchauh4n about 5 yearsyes we use .then() when we resolve .
-
amitchauh4n about 5 yearsif (answer == "worked_for_you") { vote(answer) } else {devote();}
-
John about 5 yearsThanks for clarifying, I eventually got to that solution and I can see many uses a IIFE. Yet I am still confused on how to reference that values (abc) externally to let my application work. I mean, even after main() has resolved, I can access [abc] inside the function but not outside and it does not let me assign an external variable to it
-
hackape about 5 yearsNo, no obvious solution to do that. Unless you also move that "external" code into that main function. You don't get to pass that variable externally for free.
-
hackape about 5 years@Peter You need to understand the fundamental difference btw sync/async code. The
async/await
is merely syntax sugar, it doesn't magically turn what is fundamental impossible possible. -
John about 5 yearsThat's actually what I am looking to do. I need to fetch some data and work with them on the whole application, not only inside a separate function. I am writing the app in plain JS at first and I am stuck doing this. I know in React I can save the data in store and it would be easier.
-
hackape about 5 years@Peter also did you accidentally down vote the other answer? If I misunderstand I shall apologize, but if it's you, that's not nice.
-
hackape about 5 years@Peter Yeah, you get the idea. Like with
store
, you need some kind of pub/sub mechanism to orchestrate sync/async code. That doesn't come for free, need to implement such thing. -
John about 5 yearsAll right. So what I am trying to do is actually not possible on plain JS and I need to rely on something else. Also regarding the downvote, it was not me as I am a new member and my votes are not displayed. Glad it got removed cause it actually helped me realize I missed to describe that scenario in the post as you can see in the comments
-
hackape about 5 years@Peter yep. Make sure to read this answer. And perhaps upvote/accept mine would be nice :D