NodeJS 异步等待解析图形查询承诺未解析

46qrfjad  于 2023-02-03  发布在  Node.js
关注(0)|答案(1)|浏览(140)

大家好,我正在尝试使用graphql API来获取一些国家。我正在使用这个API https://studio.apollographql.com/public/countries/home?variant=current,这是操场https://countries.trevorblades.com/
我面临的问题是我无法解决承诺。我使用的是React和fetch方法。
我的fetchCountries.js文件:

import { API_URL } from "./constants";

const COUNTRIES_QUERY = `{
  country(code: "BR") {
    name
    native
    emoji
    currency
    languages {
      code
      name
    }
  }
}`;

const fetchCountries = async () => {
  await fetch(API_URL, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      query: COUNTRIES_QUERY,
    }),
  })
    .then((response) => {
      if (response.status >= 400) {
        throw new Error("Error fetching data");
      } else {
        return response.json();
      }
    })
    .then((data) => data.data);
};

export default fetchCountries;

我在函数中使用async,wait,这样当我调用它时它就会得到解析。现在在App.js中,当我调用console.log中的fetchCountries函数时,我会得到:

Promise {<pending>}
[[Prototype]]
: 
Promise
[[PromiseState]]
: 
"fulfilled"
[[PromiseResult]]
: 
undefined

App.js:

import "./App.css";
import fetchCountries from "./api/fetchCountries";

const App = () => {
  console.log("CONSOLE LOG API", fetchCountries());

  return <div>App</div>;
};

export default App;

我也尝试过使用useEffect钩子,但得到了相同的结果:

import "./App.css";
import fetchCountries from "./api/fetchCountries";
import React, { useEffect, useState } from "react";

const App = () => {
  const [test, setTest] = useState();

  console.log("CONSOLE LOG API", fetchCountries());

  useEffect(() => {
    const getCountries = async () => {
      await fetchCountries();
    };
    setTest(getCountries());
  }, []);
  console.log("USE EFFECT API", test);

  return <div>App</div>;
};

export default App;
uyhoqukh

uyhoqukh1#

您应该按以下步骤操作

const fetchCountries = async () => {
  const response = await fetch(API_URL, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      query: COUNTRIES_QUERY,
    }),
  })
    
      if (response.status >= 400) {
        throw new Error("Error fetching data");
      } else {
        return await response.json();
      }
    
};

export default fetchCountries;

或将整个fetch.then...链括在括号内。

相关问题