How can I acces the values of my async fetch funct

2019-08-28 04:17发布

问题:

This question already has an answer here:

  • How do I return the response from an asynchronous call? 35 answers

I want to use my fetched values in another function

I'm really new to JS. So until now I tried this.setState() and a return value of the function .

async fetchData() {

    const url = 'http://localhost:8080';
    const response = await fetch(url);
    const data = await response.json();
    // stringify JSON
    var myJSON = JSON.stringify(data);
    // parsing to JS object
    var jsonData = JSON.parse(myJSON);
 }

until now, I'm getting a Promise with the status "pending" . How do I get the actual value?

回答1:

When you mark the function as async that implicitly wraps any return value it has with a Promise. You're not actually returning anything, so fetchData will just return a Promise that resolves to undefined.

So first, you need to actually return something from your function:

async fetchData() {
  const url = 'http://localhost:8080';
  const response = await fetch(url);
  const data = await response.json();
  return data; // It should already be parsed JSON since you called `response.json()`
}

Then you need to wait for the Promise to complete in the calling function:

// You can use async/await
async someOtherFunction() {
  const value = await fetchData();
  // Do things...
}

// Or use .then
someOtherFunction() {
  fetchData().then((value) => {
    // Do things...
  });
}