venus
venus3y ago

venus – 14-43 Oct 11

Hi is it possible to get rid of promise functions that throws error from promise.all array response? My solution kinda sucks cuz I am returning null on error and then removing it from array. Can you think of any better approach?
const serversPromise = servers.map(async ({ ip, port }) =>
getShortServerQuery(ip, port).catch(() => null)
);

// serversData: (Servertype | null)[]
let serversData = await Promise.all(serversPromise);

// My solution
serversData = serversData.filter((res) => res != null);
const serversPromise = servers.map(async ({ ip, port }) =>
getShortServerQuery(ip, port).catch(() => null)
);

// serversData: (Servertype | null)[]
let serversData = await Promise.all(serversPromise);

// My solution
serversData = serversData.filter((res) => res != null);
3 Replies
EvokeMe
EvokeMe3y ago
async function query(n) {
if (n === 0) throw new Error(`Cannot multiple 0`)
return n * 2
}

async function main() {
const list = [1, 2, 3, 0, 5]
return Promise.allSettled(list.map(query))
}

const log = (v) => console.log(JSON.stringify(v)) // => [{"status":"fulfilled","value":2},{"status":"fulfilled","value":4},{"status":"fulfilled","value":6},{"status":"rejected","reason":{}},{"status":"fulfilled","value":10}]
main().then(log)
async function query(n) {
if (n === 0) throw new Error(`Cannot multiple 0`)
return n * 2
}

async function main() {
const list = [1, 2, 3, 0, 5]
return Promise.allSettled(list.map(query))
}

const log = (v) => console.log(JSON.stringify(v)) // => [{"status":"fulfilled","value":2},{"status":"fulfilled","value":4},{"status":"fulfilled","value":6},{"status":"rejected","reason":{}},{"status":"fulfilled","value":10}]
main().then(log)
@venus ^^
EvokeMe
EvokeMe3y ago
reactibot
reactibot3y ago
This thread hasn’t had any activity in 12 hours, so it’s now locked. Threads are closed automatically after 12 hours. If you have a followup question, you may want to reply to this thread so other members know they're related. https://discord.com/channels/102860784329052160/565213527673929729/1029403836810526760 Question not getting answered? Maybe it's hard to answer, or maybe you asked at a slow time. Check out these resources for help asking a good question: https://stackoverflow.com/help/how-to-ask http://wp.me/p2oIwo-26

Did you find this page helpful?