我有下面的函数,我试图从数组中获取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);
}
}
1条答案
按热度按时间toe950271#
使用async to response就可以了
方法2:等待fetch调用以获取响应对象。最好在现代JavaScript中使用
const
而不是var