如何访问异步获取函数的值?

时间:2019-01-04 07:43:52

标签: javascript async-await fetch

我想在另一个函数中使用获取的值

我真的是JS新手。所以直到现在我都尝试了this.setState()和函数的返回值。

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);
 }

直到现在,我得到一个状态为“ pending”的Promise。如何获得实际值?

1 个答案:

答案 0 :(得分:3)

当您将函数标记为async时,该函数用Promise隐式包装了它具有的所有返回值。您实际上并没有返回任何内容,因此fetchData只会返回一个解析为undefined的Promise。

因此,首先,您需要从函数中实际返回一些内容:

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()`
}

然后,您需要等待Promise在调用函数中完成:

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

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