[英]Using Chained Promise.allSettled
For a quick rundown of what I'm trying to do.快速了解我正在尝试做的事情。 I've got a basic
for
loop that generates an array of IPs that I want to fetch.我有一个基本
for
循环,可以生成我想要获取的 IP 数组。 I want to check that the response.status
is 200 (Which I haven't implemented yet) and then take the IPs that returned a status of 200 and only keep those IPs.我想检查
response.status
是否为 200(我还没有实现),然后获取返回状态为 200 的 IP,并且只保留这些 IP。
I've tried doing this with Promise.all
but was left with the problem of it rejecting one, thus rejecting all of them.我试过用
Promise.all
来做这件事,但留下了它拒绝一个的问题,从而拒绝了所有这些。 So now I'm at this code.所以现在我在这个代码。
async function example() {
var arr = [];
for (let i = 4; i <= 255; i++) {
var ip = 'http://172.16.238.' + i.toString() + ':443';
arr.push(ip);
}
Promise.allSettled(arr.map(u=>fetch(u))).then(responses => Promise.allSettled(responses.map(res => res.text()))).then(texts => {fetch('https://testing.com', {method: 'POST', body: texts})})
}
example()
I'm getting res.text()
isn't a function when used with allSettled
.当与
allSettled
使用时,我得到res.text()
不是一个函数。 But I'm also confused as to how I would approach checking the status of each response.但我也对如何检查每个响应的状态感到困惑。 I'm mapping the url to each fetch and then mapping a response to it's text, so would I do the status check in the second mapping?
我将 url 映射到每个 fetch,然后将响应映射到它的文本,那么我会在第二个映射中进行状态检查吗? The mapping is a bit confusing to me.
映射对我来说有点混乱。
allSettled
does not return an array with the resolved values - rather, it returns an array of objects , where the objects contain status
/ value
/ reason
properties. allSettled
不返回具有解析值的数组 - 相反,它返回一个对象数组,其中对象包含status
/ value
/ reason
属性。 To get to the resolve value, if there is one, access the .value
property.要获取解析值(如果有),请访问
.value
属性。
But a single allSettled
will do - call .text
inside the first callback if it hasn't errored.但是一个
allSettled
就可以了——如果没有出错,在第一个回调中调用.text
。
function example() {
var arr = [];
for (let i = 4; i <= 255; i++) {
var ip = 'http://172.16.238.' + i.toString() + ':443';
arr.push(ip);
}
Promise.allSettled(arr.map(
u => fetch(u)
.then(res => { if (res.ok) return res.text(); })
))
.then(results => {
const texts = results
.filter(result => result.status === 'fulfilled' && result.value)
.map(result => result.value);
fetch('https://testing.com', { method: 'POST', body: texts })
// ...
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.