使用 async await 获取数据时,我必须使用 try catch 还是 then catch [重复]

问题描述 投票:0回答:2

我正在使用

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
吗?

javascript async-await promise try-catch
2个回答
0
投票

尝试{ 控制台日志(结果); } 赶上(错误){ console.error(错误);

enter code here
}

你可以做这样的事情来获取响应,尝试成功响应,如果有错误则失败并捕获。


-1
投票

看看这个什么时候使用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}`);
  });

© www.soinside.com 2019 - 2024. All rights reserved.