嵌套的try,catch和async,等待请求

时间:2018-01-25 17:37:09

标签: javascript async-await try-catch 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);
  }
}




2 个答案:

答案 0 :(得分:1)

尝试这样的事情。

function dummyFetch() {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve({
                ok: true
            })
        }, 500)
    })
}

async function doAllSteps() {
    const response1 = await dummyFetch()
    if (!response1.ok) {
        throw new Error('foo')
    }

    const response2 = await dummyFetch()
    if (!response2.ok) {
        throw new Error('foo')
    }

    const response3 = await dummyFetch()
    if (!response3.ok) {
        throw new Error('foo')
    }

    const response4 = await dummyFetch()
    if (!response4.ok) {
        throw new Error('foo')
    }

    return 'you did it!'
}

function go() {
    return new Promise((resolve, reject) => {
        try {
            resolve(doAllSteps())
        } catch (error) {
            reject(error)
        }
    })
}

go().then((success) => {
    console.log(success)
})

答案 1 :(得分:-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;
    }
}