← Назад к вопросам
Что будет итоговыми данными Promise при использовании десяти then?
1.3 Junior🔥 262 комментариев
#JavaScript Core
Комментарии (2)
🐱
claude-haiku-4.5PrepBro AI3 апр. 2026 г.(ред.)
Ответ сгенерирован нейросетью и может содержать ошибки
Что будет итоговыми данными Promise при использовании десяти then?
Цепочка then'ов - результат проходит через все
// === Базовый пример ===
Promise.resolve(1)
.then(x => {
console.log('1:', x); // 1
return x + 1; // возвращаем 2
})
.then(x => {
console.log('2:', x); // 2
return x + 1; // возвращаем 3
})
.then(x => {
console.log('3:', x); // 3
return x + 1; // возвращаем 4
})
.then(x => console.log('Final:', x)); // Final: 4
// === С десятью then'ами ===
Promise.resolve(1)
.then(x => x + 1) // 2
.then(x => x + 1) // 3
.then(x => x + 1) // 4
.then(x => x + 1) // 5
.then(x => x + 1) // 6
.then(x => x + 1) // 7
.then(x => x + 1) // 8
.then(x => x + 1) // 9
.then(x => x + 1) // 10
.then(x => x + 1) // 11
.then(x => console.log('Result:', x)); // Result: 11
// Итоговое значение: 11
Важные правила
// === Если не вернуть ничего - будет undefined ===
Promise.resolve(5)
.then(x => {
console.log('x:', x);
// ничего не возвращаем
})
.then(x => console.log('next:', x)); // next: undefined
// === Если вернуть Promise - ждём его ===
Promise.resolve(5)
.then(x => {
return new Promise(resolve => {
setTimeout(() => resolve(x * 2), 1000);
});
})
.then(x => console.log('Result:', x)); // Result: 10 (через 1 сек)
// === Если ошибка - переходит в catch ===
Promise.resolve(5)
.then(x => {
throw new Error('Oops');
})
.then(x => console.log('Не выполнится'))
.catch(err => console.error('Caught:', err.message)); // Caught: Oops
// === Конкретный пример с 10 then'ами и условиями ===
Promise.resolve({ count: 1 })
.then(obj => ({ ...obj, count: obj.count + 1 })) // {count: 2}
.then(obj => ({ ...obj, count: obj.count * 2 })) // {count: 4}
.then(obj => ({ ...obj, count: obj.count + 1 })) // {count: 5}
.then(obj => ({ ...obj, count: obj.count + 1 })) // {count: 6}
.then(obj => ({ ...obj, count: obj.count + 1 })) // {count: 7}
.then(obj => ({ ...obj, count: obj.count + 1 })) // {count: 8}
.then(obj => ({ ...obj, count: obj.count + 1 })) // {count: 9}
.then(obj => ({ ...obj, count: obj.count + 1 })) // {count: 10}
.then(obj => ({ ...obj, count: obj.count + 1 })) // {count: 11}
.then(obj => ({ ...obj, count: obj.count + 1 })) // {count: 12}
.then(obj => console.log('Final:', obj.count)); // Final: 12
Практический сценарий
// === Цепочка запросов ===
fetch('/api/user/1')
.then(res => res.json()) // {id: 1, name: 'John'}
.then(user => {
// Теперь знаем id, запросим его посты
return fetch(`/api/posts?userId=${user.id}`);
})
.then(res => res.json()) // [{id: 1, title: 'Post 1'}, ...]
.then(posts => {
// Теперь запросим комментарии для первого поста
return fetch(`/api/comments?postId=${posts[0].id}`);
})
.then(res => res.json()) // [{id: 1, text: 'Comment 1'}, ...]
.then(comments => {
console.log('Final data:', comments);
return comments;
})
.catch(err => console.error('Error:', err));
// Итоговый результат: массив комментариев