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.
To assign value from successful promise resolve to external variable with JavaScript, we use async and await. const myFunction = async () => { vm. feed = await getFeed(); // ... }; to get the resolve value of the promise returned by getFeed with await .
Promise resolve() method: If the value is a promise then promise is returned. If the value has a “then” attached to the promise, then the returned promise will follow that “then” to till the final state. The promise fulfilled with its value will be returned.
resolve() method "resolves" a given value to a Promise . If the value is a promise, that promise is returned; if the value is a thenable, Promise. resolve() will call the then() method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value.
Yes, the values in results are in the same order as the promises .
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With