幕后的 Try-Catch 功能

Try-Catch functionality behind the scenes

想象一下这样的代码块,我在 post 下方请求尚未显示的评论(可能有一个按钮可以加载更多评论)。

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");
}

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

My question is: if there is an error in receiving the comments, the try is immediately aborted or it continued...

当错误发生时,控制从 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