Sobes.tech
Назад к вопросам
Middle+
3

console.log(1) setTimeout(() => { console.log(2) }, 10) setTimeout(() => { Promise.resolve().then(() => console.log(3)) }, 0); setTimeout(() => { console.log(4) }, 0); new Promise((_, reject) => { console.log(5) reject(6) console.log(7) }).then(() => console.log(8)) .catch(() => console.log(9)) .then(() => console.log(10)) .catch(() => console.log(11)) .then(() => console.log(12)) .then(console.log) .finally(() => console.log(13)) console.log(14)

Компании, где спрашивали
Mayflower

Ответ от нейросети

sobes.tech AI

Разберём порядок вывода в консоль по шагам:

console.log(1)

setTimeout(() => {
    console.log(2)
}, 10)

setTimeout(() => {
    Promise.resolve().then(() => console.log(3))
}, 0);

setTimeout(() => {
    console.log(4)
}, 0);

new Promise((_, reject) => {
    console.log(5)
    reject(6)
    console.log(7)
}).then(() => console.log(8))
  .catch(() => console.log(9))
  .then(() => console.log(10))
  .catch(() => console.log(11))
  .then(() => console.log(12))
  .then(console.log)
  .finally(() => console.log(13))

console.log(14)
  1. Синхронный код выполняется сразу:

    • console.log(1) → 1
    • В конструкторе промиса: console.log(5) → 5
    • console.log(7) → 7
    • console.log(14) → 14
  2. Промис отклонён (reject(6)), поэтому цепочка .catch() срабатывает.

  3. Микротаски (Promise handlers) выполняются после текущего стека:

    • .catch(() => console.log(9)) → 9
    • .then(() => console.log(10)) → 10
    • .catch() пропускается, так как нет ошибки
    • .then(() => console.log(12)) → 12
    • .then(console.log) — получает undefined (результат предыдущего then), выводит undefined
    • .finally(() => console.log(13)) → 13
  4. Макротаски (setTimeout) срабатывают после микротасков:

    • setTimeout(..., 0) с Promise.resolve().then(() => console.log(3)) — сначала срабатывает setTimeout, внутри которого создаётся микротаск, который выводит 3
    • setTimeout(..., 0) с console.log(4) — выводит 4
    • setTimeout(..., 10) с console.log(2) — выводит 2

Итоговый порядок вывода:

1
5
7
14
9
10
12
undefined
13
3
4
2

Объяснение:

  • Сначала синхронный код.
  • Затем обработчики промисов (микротаски).
  • Потом setTimeout с 0 задержкой (макротаски), внутри которых могут быть микротаски.
  • Наконец, setTimeout с задержкой 10 мс.