在下面的代码中,我们尝试获取多个网址,并在响应返回时处理错误。
我注意到这里使用了 2 个 Promise.all
。为什么需要使用第二个Promise.all
?当你删除它时会发生什么?
Promise.all( //1st one
urls.map(url => fetch(url).catch(err => err))
)
.then(responses => Promise.all( //2nd one
// if it's an error then pass on
// otherwise response.json() and catch errors as results
responses.map(r => r instanceof Error ? r : r.json().catch(err => err))
))
.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)
});
最佳答案
第二个 Promise.all()
将所有成功响应映射到 JSON。
因为Response.json()
本身返回一个 promise ,来自 responses.map(...)
的结果数组可能看起来像
[ error, Promise<Object>, Promise<Object>, error, Promise<Object> ]
为了等待所有 json()
promise 解析,您需要使用第二个 Promise.all()
。
数组中的非promise将被视为Promise.resolve(item)
请注意,这段代码可以写得更简洁(请参阅其他答案)。这个答案更像是“为什么代码是这样的” 🙂
关于javascript - 为什么在http请求获取和响应中需要两个 `Promise.all`实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55526976/