如果我在控制台中查看,它将给我:
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。
这是异步等待的方式
const fetchCourses = async args => {
const res = await fetch(`/coursemanagement/getschoolcourse`, {
method: "POST",
body: JSON.stringify({ schoolId: currentSchool2 }),
headers: {
"Content-Type": "application/json"
}
});
const body = await res.json();
console.log("coursesbody is:", body)
return body;
};
// here is how you call this function
const data = await fetchCourses();
// If you have multiple functions and data from one function is being used in second and so on then you can do something like
const schools= await getSchools();
const courses = await getCourses(schools);
const docents = await fetchDocents(courses);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句