Как ждать ответа fetch в функции asyn c? - PullRequest
0 голосов
/ 08 января 2020

Если я загляну в консоль, она выдаст мне:

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()
    })
  };

Как правильно ждать ответа. Мне трудно обернуть голову вокруг await / asyn c в js.

РЕДАКТИРОВАТЬ: В использованииEffect я сейчас вызываю

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 при первом получении

1 Ответ

0 голосов
/ 08 января 2020

Вот как вы делаете асин c жду

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);
...