[英]async await resolve graphql query promise not resolved
Hi All i am trying to use graphql api to fetch some country.大家好我正在尝试使用 graphql api 获取一些国家。 I am using this API https://studio.apollographql.com/public/countries/home?variant=current and this is playground https://countries.trevorblades.com/我正在使用这个 API https://studio.apollographql.com/public/countries/home?variant=current这是游乐场https://countries.trevorblades.com/
The problem i am facing is that i cannot resolve the Promise. I am using React and fetch
method.我面临的问题是我无法解析 Promise。我正在使用 React 和fetch
方法。
my fetchCountries.js file:我的 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;
i am using async, await in the function so that it gets resolved when i call it.我正在使用异步,在 function 中等待,以便在我调用它时得到解决。 Now in my App.js when i call fetchCountries function in console.log i get:现在在我的 App.js 中,当我在 console.log 中调用 fetchCountries function 时,我得到:
Promise {<pending>}
[[Prototype]]
:
Promise
[[PromiseState]]
:
"fulfilled"
[[PromiseResult]]
:
undefined
App.js:应用程序.js:
import "./App.css";
import fetchCountries from "./api/fetchCountries";
const App = () => {
console.log("CONSOLE LOG API", fetchCountries());
return <div>App</div>;
};
export default App;
I have also tried to use useEffect hook but got the same result:我也尝试过使用 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;
You should do it as follows你应该这样做如下
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;
Or enclose entire fetch.then...
chain inside paranthesis.或者将整个fetch.then...
链包含在括号内。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.