Обробка помилок у Promise та async/await:
function fetchWithTimeout(ms) {
return new Promise((resolve, reject) => {
if (ms > 100) return reject(new Error('Timeout'));
setTimeout(() => resolve('Дані отримано'), ms);
});
}
fetchWithTimeout(50)
.then(d => console.log(d))
.catch(e => console.log('Помилка:', e.message));
fetchWithTimeout(200)
.then(d => console.log(d))
.catch(e => console.log('Помилка:', e.message));
async function validate(item) {
if (item < 0) throw new Error(`${item} від'ємне`);
return item * 2;
}
async function processItems(items) {
const good = [], bad = [];
for (const item of items) {
try { good.push(await validate(item)); }
catch (e) { bad.push(e.message); }
}
console.log(`Успішно: ${good}`);
console.log(`Помилки: ${bad.length}`);
}
processItems([5, -2, 8, -1, 3]);
const nums = [4, 0, 9, -1, 16];
const promises = nums.map(n =>
n > 0 ? Promise.resolve(Math.sqrt(n).toFixed(2)) : Promise.reject(new Error('Неможливо взяти корінь'))
);
Promise.allSettled(promises).then(results => {
results.forEach(r => {
if (r.status === 'fulfilled') console.log(`OK: ${r.value}`);
else console.log(`FAIL: ${r.reason.message}`);
});
});