【发布时间】:2020-01-08 16:59:28
【问题描述】:
如果我查看控制台,它会给我:
coursesbody is:
Promise { "pending" }
<state>: "pending"
const fetchCourses = async args => {
await fetch(`/coursemanagement/getschoolcourse`, {
method: "POST",
body: JSON.stringify({ schoolId: currentSchool2 }),
headers: {
"Content-Type": "application/json"
}
}).then(res =>{
const body = res.json();
console.log("coursesbody is:", body)
return res.json()
})
};
等待响应的正确方法是什么。我很难理解 js 中的 await/async。
编辑: 在 useEffect 我现在正在调用
useEffect(() => {
setSchoolsCoursesDocents()
}
setSchoolsCoursesDocents() 是:
const setSchoolsCoursesDocents = async () => {
const schools= await fetchSchools();
const courses = await fetchCourses(schools);
const docents = await fetchDocents(courses);
};
fetchSchools 看起来像:
const fetchSchools = async () => {
const result = await fetch(`/coursemanagement/getschools`, {
method: "GET"
});
const body = await result.json();
setSchools(body);
setCurrentSchool1(body[0].id)
setCurrentSchool2(body[0].id)
};
然后将状态 currentSchool2 用于:
const fetchCourses = async args => {
console.log("currentSchool2 is", currentSchool2)
const result = await fetch(`/coursemanagement/getschoolcourse`, {
method: "POST",
body: JSON.stringify({ schoolId: currentSchool2 }),
headers: {
"Content-Type": "application/json"
}
});
const body = await result.json();
setCourses(body);
setCurrentCourse(body[0].courseId);
};
但是 console.log 是未定义的,但是 currentSchool2 应该在第一次获取时设置为 1
【问题讨论】:
-
res.json()返回一个承诺。您需要等待它才能得到结果。您直接记录它,这就是为什么您会看到Promise { pending } -
您需要将所需的数据作为参数传递,而不是使用将异步更新且不会在消费时提供更新值的状态变量。
-
是的,谢谢你。非常非常感谢!
标签: javascript reactjs async-await