下面的代码取自https://javascript.info/promise-api的最后一个任务。
当我运行以下命令时,我无法获得与注释指示的警报相匹配的输出。我假设我在catch语句中遗漏了一些东西,但我不知道我错在哪里。感谢大家的帮助!
// the whole promise chain fails with an error here
// change that:
// make errors appear as members of the results array
let urls = [
'https://api.github.com/users/iliakan',
// this URL is HTML page, it's invalid JSON, so response.json() fails
'/',
// this URL is invalid, so fetch fails
'http://no-such-url'
];
// Fix it:
Promise.all(urls.map(url => fetch(url).catch(err=>err)))
.then(responses => Promise.all(
responses.map(r => r.json().catch(err=>err))
))
// Demo output (no need to change):
.then(results => {
alert(results[0].name); // Ilya Kantor
alert(results[1]); // SyntaxError: Unexpected token < in JSON at position 0
alert(results[2]); // TypeError: failed to fetch (text may vary)
});
发布于 2019-03-08 15:40:55
你确实从你的代码中得到一个错误。例如,在火狐中,它会在开发者控制台中显示TypeError: r.json is not a function。(我看到您使用的是alert(),所以您可能不熟悉浏览器中提供的开发人员控制台和console.log()。如果是这样的话,我建议研究一下他们,因为他们提供的信息可能是无价的。)
问题是,在r.json()中,由于前面的第一个.catch(err=>err),r要么是响应对象,要么是异常对象。因为异常对象没有json属性,所以它会抛出自己的异常。这个异常没有被捕获,因为没有用于它的try/catch,并且.catch()只能在promises上使用。
您可以执行以下操作来检查并传递初始异常:
responses.map(r => r.json ? r.json().catch(err=>err) : r)发布于 2019-03-08 15:22:26
这不起作用的原因是,在第一个.catch(err=>err)语句中,它将错误视为标准(成功)结果。然后,fetch中的任何错误数据都被调用到下一个Promise.all语句中,因为它被视为一个好的结果,因此r.json()将不知道如何处理任何错误数据(来自fetch('/') )。
https://stackoverflow.com/questions/55056875
复制相似问题