首页 > 解决方案 > 如何访问我的异步获取函数的值?

问题描述

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

我对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。我如何获得实际价值?

标签: javascriptasync-awaitfetch

解决方案


当您将函数标记为async隐式包装它具有 Promise 的任何返回值时。你实际上并没有返回任何东西,所以fetchData只会返回一个解析为undefined.

所以首先,你需要从你的函数中实际返回一些东西:

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

推荐阅读