Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save results of a promise to a variable? [duplicate]

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.

like image 634
John Avatar asked Apr 09 '19 15:04

John


People also ask

How do you assign a promise result to a variable?

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 .

How do I get a value returned from promise?

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.

What does resolve () do in a promise?

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.

Does promise all always return same order?

Yes, the values in results are in the same order as the promises .


1 Answers

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();
like image 191
hackape Avatar answered Nov 04 '22 09:11

hackape