我正在使用
fetch
和 async await
来获取数据:
const getData = async () => {
const response = await fetch(process.env.ENDPOINT, options);
const json = response.json();
return json;
};
try {
getData().then((result) => {
console.log(result);
});
} catch (error) {
console.log('There was an error', error);
}
我必须像上面那样使用
try catch
或then catch
吗?
尝试{ 控制台日志(结果); } 赶上(错误){ console.error(错误);
enter code here
}
你可以做这样的事情来获取响应,尝试成功响应,如果有错误则失败并捕获。
看看这个什么时候使用try-catch和then-catch
在你的情况下它会像
const getData = async () => {
try {
const response = await fetch(process.env.ENDPOINT, options);
const json = response.json();
return json;
}
catch(error) {
// catch error
}
};
getData().then((result) => {
console.log(result);
res.redirect(`/rtl-boulevard/?videoId=${result.data.page.content.uuid}`);
});