Skip to content

Commit 6c89a41

Browse files
authored
Merge pull request #2 from OshekharO/copilot/fix-fetch-results-issue
fix: use Promise.allSettled to prevent single-source failure from discarding all results
2 parents 3ce8ea3 + 3b1bc48 commit 6c89a41

1 file changed

Lines changed: 10 additions & 6 deletions

File tree

app.js

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -87,15 +87,19 @@ async function find(search) {
8787
const base = 'https://news-api-mocha.vercel.app/api/torrent';
8888
const encoded = encodeURIComponent(search);
8989

90-
const [res1, res2] = await Promise.all([
91-
fetch(`${base}/nyaasi/${encoded}`),
92-
fetch(`${base}/piratebay/${encoded}`)
90+
const [result1, result2] = await Promise.allSettled([
91+
fetch(`${base}/nyaasi/${encoded}`).then(r => { if (!r.ok) throw new Error(`HTTP ${r.status}`); return r.json(); }),
92+
fetch(`${base}/piratebay/${encoded}`).then(r => { if (!r.ok) throw new Error(`HTTP ${r.status}`); return r.json(); })
9393
]);
9494

95-
let [data1, data2] = await Promise.all([res1.json(), res2.json()]);
95+
if (result1.status === 'rejected' && result2.status === 'rejected') {
96+
const err = new Error('Both sources failed');
97+
err.reasons = [result1.reason, result2.reason];
98+
throw err;
99+
}
96100

97-
if (!Array.isArray(data1)) data1 = [];
98-
if (!Array.isArray(data2)) data2 = [];
101+
let data1 = (result1.status === 'fulfilled' && Array.isArray(result1.value)) ? result1.value : [];
102+
let data2 = (result2.status === 'fulfilled' && Array.isArray(result2.value)) ? result2.value : [];
99103

100104
data1 = data1.map(item => ({ ...item, _source: 'NyaaS' }));
101105
data2 = data2.map(item => ({ ...item, _source: 'PirateBay' }));

0 commit comments

Comments
 (0)