axios 请求返回 promise 对象

Axios request returning promise Object

不知道为什么当我在执行 fetchPrice() 方法后注销价格时,返回的是一个承诺对象而不是价格。请帮助:)

async function fetchPrice() {
    await axios
      .get(assetData(selectedAsset))
      .then((response) => {
        return response.data.market_data.current_price.eur;
      })
      .catch((error) => console.log(error.response.data.error));
  }

  useEffect(() => {
    let price = fetchPrice();
    console.log("Asset Price: " + price);

    let assetTotal = Number(cost) / Number(price);
    setAssetAmount(assetTotal);
  }, [selectedAsset]);

问题在于您如何处理函数的 await。通常,在使用 promise 时,您会使用 await 或回调,而不是同时使用两者。因为 await 已经等待 promise 解决或抛出错误,所以您直接在函数内部使用 return 而不是在回调中使用

async function fetchPrice() {
  try {
    const price = await axios.get(assetData(selectedAsset));
    return price;
  } catch (e) {
    console.log(error.response.data.error)
  }
}

在回调中使用 return 不会 return 您期望的对象,因为它是回调函数的结果而不是原始函数。

由于 fetchPrice 是一个异步函数,因此如果您尝试打印它,您将获得一个承诺是正常的。即使您按照我上面告诉您的那样更正您的功能,这也不会改变。获取该对象的唯一方法是在 useEffect 中等待您的获取价格(并使 useEffect 本身异步),如下所示:

useEffect(async () => {
    let price = await fetchPrice();
    console.log("Asset Price: " + price);

    let assetTotal = Number(cost) / Number(price);
    setAssetAmount(assetTotal);
  }, [selectedAsset]);

但是,如果你这样做,你会得到以下警告,因为你的使用效果使用应该是同步的:

Effect callbacks are synchronous to prevent race conditions. Put the async function inside

最终的解决方案?直接在回调中设置状态。

async function fetchPrice(cost) {
  try {
    const price = await axios.get(assetData(selectedAsset));
    setAssetAmount(Number(cost)/Number(price))
  } catch (e) {
    console.log(error.response.data.error)
  }
}

但是,在可以卸载的组件中异步设置状态时要小心内存泄漏。

您需要使用 .then()async/await

then()的例子

 useEffect(() => {
    axios.get("https://api.github.com/users/mapbox").then((response) => {
      console.log(response.data);
    });
  }, []);

In above code, we are using .then() so then will be fired when api call is done.

async/await

的例子
  async function axiosTest() {
    const response = await axios.get("https://api.github.com/users/mapbox");
    console.log(response.data, "with await");
  }

In above code, we are using await to wait until the api call is done.

这里是 Codesandbox 检查与实时 api 调用的区别