[ Web Proxy ]
URL:
Viewing: https://ar.javascript.info/microtask-queue [Back]  [Original]

:
Light themeDark theme
DanskEnglishEspaolFranaisIndonesiaItalianoTrkeOzbek

Promise .then/.catch/.finally

promise _ _ .then /.catch / .finally .

:

let promise = Promise.resolve();

promise.then(() => alert('promise done!'));

alert('code finished'); // this alert shows first

, code finished , promise done!.

promise .

.then

Asynchronous tasks need proper management. For that, the ECMA standard specifies an internal queue PromiseJobs, more often referred to as the microtask queue (V8 term).

[] (https://tc39.github.io/ecma262/#sec-jobs-and-job-queues):

  • : .
  • .

then / catch / . JavaScript .

. []

.

.then / catch / . .

** **

".then`:

Promise.resolve()
  .then(() => alert('promise done!'))
  .then(() => alert('code finished'));

.

unhandledrejection <info: promo-error-handling>

.

** . **

.catch :

let promise = Promise.reject(new Error("Promise Failed!"));
promise.catch(err => alert('caught'));

// doesn't run: error handled
window.addEventListener('unhandledrejection', event => alert(event.reason));

.catch :

let promise = Promise.reject(new Error('Promise Failed!'));

// Promise Failed!
window.addEventListener('unhandledrejection', (event) => alert(event.reason));

:

let promise = Promise.reject(new Error("Promise Failed!"));
setTimeout(() => promise.catch(err => alert('caught')), 1000);

// Error: Promise Failed!
window.addEventListener('unhandledrejection', event => alert(event.reason));

! .

: !

: .

.catch setTimeout . .

Promise handling is always asynchronous, as all promise actions pass through the internal promise jobs queue, also called microtask queue (V8 term).

.then / catch / .

.then / catch / .then .

Node.js . <info: event-loop>.


Web Proxy Viewer  |  New URL  |  Original Page