【问题标题】:How to wait for response of fetch in async function?如何在异步函数中等待 fetch 的响应?
【发布时间】: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


【解决方案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);

【讨论】:

  • 谢谢,我怎么能连接多个函数,让第二个等待第一个完成等等?比如:fetchSchools().then(() => fetchCourses()).then(() => fetchDocents());我需要它,因为我正在存储第二次提取所需的第一次提取的结果。
  • @leabum 我更新了解决此评论的答案
  • 谢谢。问题是我正在做反应,它告诉我等待不能在异步函数之外使用。我在 useEffect 中调用 getSchools() 之类的函数。
  • 是的,您需要在 useEffect 之外创建一个异步函数,并从 useEffect 中调用该函数。或者你可以在 useEffect 回调中声明和调用函数
  • 我创建了 const setSchoolsCoursesDocents = async () =&gt; { const schools= await fetchSchools(); const courses = await fetchCourses(schools); const docents = await fetchDocents(courses); };,我现在在我的 useEffect 中调用它。在 fetchSchools() 我设置 setCurrentSchool2(body[0].id) 但如果我在 fetchCourses() 内设置console.log("currentSchool2 is", currentSchool2) 它会给我未定义,这会导致问题。我认为执行顺序仍然是关闭的。 currentSchool2 是一个状态。
猜你喜欢
  • 1970-01-01
  • 2018-06-03
  • 2011-09-03
  • 2013-08-29
  • 1970-01-01
  • 2021-08-09
  • 2018-09-29
  • 2020-12-03
相关资源
最近更新 更多