【问题标题】:Try-Catch functionality behind the scenes幕后的 Try-Catch 功能
【发布时间】:2021-07-02 11:10:46
【问题描述】:

想象一下这样的代码块,我要求在帖子下方显示尚未显示的 cmets(可能有一个加载更多 cmets 的按钮)。

try {
  const postId = post._id;
  const res = await axios.get(
    `${baseUrl}/api/posts/moreComments/${postId}`,
    {
      params: { yetDisplayedLength },
    }
  );

  const newComments = res.data.comments;

  setComments((comments) => [...comments, ...newComments]);

  setCommentsLength(res.data.commentsLength);
} catch (error) {
  alert(error + "\n Error loading more comments");
}

我的问题是:如果在接收 cmets 时出错,尝试立即中止或继续,然后仍然设置 cmets (setComments((comments) => [...comments, ...newComments]);)? 我问这个是因为在 catch 块中我不知道是否必须像以前那样设置 cmets 状态 (setComments((comments) => comments.pop()))

【问题讨论】:

  • 一旦出现错误,代码执行就会停止并跳转到catch 块。例如,如果axios.get() 失败,您将不会得到newCommentssetComments 也不会运行,setCommentsLength 也不会运行。从逻辑上讲,它们无法运行,甚至-您如何使 cmets 无中生有? axios.get 甚至没有返回 null 或任何东西,只是出错了。
  • 我认为 axios.get 可以处理返回 null 或类似的东西,但在你评论的最后一行你澄清了它。谢谢 VLAZ

标签: javascript reactjs ecmascript-6 try-catch


【解决方案1】:

我的问题是:如果接收 cmets 出现错误,尝试立即中止或继续...

当错误发生时,控制从try 块转移到catch立即,而不是稍后。见MDN's writeup

你也可以试试:

function fail() {
    return new Promise((resolve, reject) => {
        setTimeout(reject, 100, new Error("failed"));
    });
}

async function example() {
    try {
        console.log("A");
        await fail();
        console.log("B");
    } catch (e) {
        console.log("error:", e.message);
    }
}

example();

请注意,您只会看到出现错误之前记录的 A,而不是 AB

【讨论】:

    猜你喜欢
    • 2011-12-14
    • 2019-10-14
    • 1970-01-01
    • 2019-05-26
    • 2021-01-15
    • 1970-01-01
    • 2014-04-27
    • 2011-04-09
    • 1970-01-01
    相关资源
    最近更新 更多