javascript 仅在状态码成功的情况下检索fetch的结果对象

mutmk8jj  于 2023-05-21  发布在  Java
关注(0)|答案(1)|浏览(125)

我有下面的函数,我试图从数组中获取JSON,如果成功,则更新相应的状态对象。
从代码中可以看出,我只想在请求成功的情况下尝试从结果中检索信息。response.status == 200。但是,我无法在if块下使用await,因为它只能在async函数下直接使用。
在这种情况下,如何在尝试检索对象之前等待对象可用?

async function FetchMovies() {
    try {
      const movies = await fetch(url, {
        method: 'GET',
        headers: {
          'Accept': 'application/json',
          'authorization': token
        },
      }).then((response) => {
        if (response.status == 200) {
          var results = await movies.json(); // await keyword is only allowed in async function or at the top level or a module
          if (results.length > 0) {
            movies_options = results;
            setMovies(movies_options);
          }
        }
        else {
          console.log(response.status);
        }
      });
    } catch (e) {
      console.log(e);
    }
  }
toe95027

toe950271#

使用async to response就可以了

async function FetchMovies() {
    try {
      const movies = await fetch(url, {
        method: 'GET',
        headers: {
          'Accept': 'application/json',
          'authorization': token
        },
      }).then(async (response) => {// using async here
        if (response.status == 200) {
          var results = await movies.json(); 
          if (results.length > 0) {
            movies_options = results;
            setMovies(movies_options);
          }
        }
        else {
          console.log(response.status);
        }
      });
    } catch (e) {
      console.log(e);
    }
  }

方法2:等待fetch调用以获取响应对象。最好在现代JavaScript中使用const而不是var

async function FetchMovies() {
    try {
      const movies = await fetch(url, {
        method: 'GET',
        headers: {
          'Accept': 'application/json',
          'authorization': token
        },
      })
         if (movies.status === 200) {
      const results = await movies.json();
      if (results.length > 0) {
        movies_options = results;
        setMovies(movies_options);
      }
    } else {
      console.log(movies.status);
    }
  } catch (error) {
    console.log(error);
  }
}

相关问题