嵌套的 try、catch 和 async、await 请求

Rya*_*n K 5 javascript try-catch async-await fetch-api

我正在尝试使用 fetch() 发出三个请求,每个请求都取决于前一个请求的结果。如果任何请求失败,我想抛出一个自定义错误。

这种模式有效,除非最里面的请求失败,它会抛出所有三个错误。如果中间请求失败,则抛出中间和外部错误。

我该如何解决这个问题,让它只从请求失败的级别抛出错误?有没有更好的方法来写这个?

async function requests() {
  try {
    let response1 = await fetch();
    if (response1.ok) {
      try {
        let response2 = await fetch();
        if (response2.ok) {
          try {
            let response3 = await fetch();
            if (response3.ok) {
              let jsonResponse3 = response3.json();
              return jsonResponse3;
            }
            throw new Error('Request 3 failed');
          } catch (error) {
            console.log(error);
          }
        }
        throw new Error('Request 2 failed');
      } catch (error) {
        console.log(error);
      }
    }
    throw new Error('Request 1 failed');
  } catch (error) {
    console.log(error);
  }
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*erg -2

你能一个接一个地做而不是嵌套吗?

async function requests() {
    try {
        let response1 = await fetch();
        throw new Error('Request 1 failed');
    } catch (error) {
        console.log(error);
    }
    if (response1 && response1.ok) {
        try {
            let response2 = await fetch();
            throw new Error('Request 2 failed');
        } catch (error) {
            console.log(error);
        }
    }
    if (response2 && response2.ok) {
        try {
            let response3 = await fetch();
            throw new Error('Request 3 failed');
        } catch (error) {
            console.log(error);
        }
    }
    if (response3 && response3.ok) {
        let jsonResponse3 = response3.json();
        return jsonResponse3;
    }
}
Run Code Online (Sandbox Code Playgroud)