The Promise object represents the eventual completion (or failure) of an asynchronous operation và its resulting value.

Bạn đang xem: Typescript programming with visual studio code

To learn about the way promises work and how you can use them, we advise you to read Using promises first.

A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to lớn associate handlers with an asynchronous action"s eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise lớn supply the value at some point in the future.

A Promise is in one of these states:

pending: initial state, neither fulfilled nor rejected. fulfilled: meaning that the operation was completed successfully. rejected: meaning that the operation failed.

A pending promise can either be fulfilled with a value or rejected with a reason (error). When either of these options happens, the associated handlers queued up by a promise"s then method are called. If the promise has already been fulfilled or rejected when a corresponding handler is attached, the handler will be called, so there is no race condition between an asynchronous operation completing and its handlers being attached.

As the Promise.prototype.then() và Promise.prototype.catch() methods return promises, they can be chained.


Note: Several other languages have mechanisms for lazy evaluation and deferring a computation, which they also điện thoại tư vấn "promises", e.g. Scheme. Promises in JavaScript represent processes that are already happening, which can be chained with callback functions. If you are looking to lớn lazily evaluate an expression, consider using a function with no arguments e.g. F = () => expression khổng lồ create the lazily-evaluated expression, & f() khổng lồ evaluate the expression immediately.

Note: A promise is said lớn be settled if it is either fulfilled or rejected, but not pending. You will also hear the term resolved used with promises — this means that the promise is settled or "locked-in" to match the state of another promise. States và fates contain more details about promise terminology.

Chained Promises

The methods Promise.prototype.then(), Promise.prototype.catch(), & Promise.prototype.finally() are used khổng lồ associate further action with a promise that becomes settled.

The .then() method takes up to lớn two arguments; the first argument is a callback function for the resolved case of the promise, and the second argument is a callback function for the rejected case. Each .then() returns a newly generated promise object, which can optionally be used for chaining; for example:

const myPromise = new Promise((resolve, reject) => setTimeout(() => resolve("foo"); , 300););myPromise .then(handleResolvedA, handleRejectedA) .then(handleResolvedB, handleRejectedB) .then(handleResolvedC, handleRejectedC);
Processing continues khổng lồ the next liên kết of the chain even when a .then() lacks a callback function that returns a Promise object. Therefore, a chain can safely omit every rejection callback function until the final .catch().

Xem thêm: Vnpt Dịch Vụ Internet - Gói Cước Home Internet

Handling a rejected promise in each .then() has consequences further down the promise chain. Sometimes there is no choice, because an error must be handled immediately. In such cases we must throw an error of some type lớn maintain error state down the chain. On the other hand, in the absence of an immediate need, it is simpler khổng lồ leave out error handling until a final .catch() statement. A .catch() is really just a .then() without a slot for a callback function for the case when the promise is resolved.

Using Arrow Function Expressions for the callback functions, an implementation of a promise chain might look something like this:

promise1.then(value => return value + " & bar"; ).then(value => return value + " và bar again"; ).then(value => return value + " & again"; ).then(value => return value + " và again"; ).then(value => console.log(value) ).catch(err => console.log(err) );
The termination condition of a promise determines the "settled" state of the next promise in the chain. A "resolved" state indicates a successful completion of the promise, while a "rejected" state indicates a lack of success. The return value of each resolved promise in the chain is passed along khổng lồ the next .then(), while the reason for rejection is passed along lớn the next rejection-handler function in the chain.

The promises of a chain are nested lượt thích Russian dolls, but get popped like the đứng đầu of a stack. The first promise in the chain is most deeply nested và is the first to lớn pop.

(promise D, (promise C, (promise B, (promise A) ) ) )
When a nextValue is a promise, the effect is a dynamic replacement. The return causes a promise to lớn be popped, but the nextValue promise is pushed into its place. For the nesting shown above, suppose the .then() associated with "promise B" returns a nextValue of "promise X". The resulting nesting would look like this:

(promise D, (promise C, (promise X) ) )
A promise can participate in more than one nesting. For the following code, the transition of promiseA into a "settled" state will cause both instances of .then() lớn be invoked.

const promiseA = new Promise(myExecutorFunc);const promiseB = promiseA.then(handleFulfilled1, handleRejected1);const promiseC = promiseA.then(handleFulfilled2, handleRejected2);
An kích hoạt can be assigned lớn an already "settled" promise. In that case, the action (if appropriate) will be performed at the first asynchronous opportunity. Note that promises are guaranteed lớn be asynchronous. Therefore, an kích hoạt for an already "settled" promise will occur only after the stack has cleared và a clock-tick has passed. The effect is much lượt thích that of setTimeout(action,10).

const promiseA = new Promise( (resolutionFunc,rejectionFunc) => resolutionFunc(777););// At this point, "promiseA" is already settled.promiseA.then( (val) => console.log("asynchronous logging has val:",val) );console.log("immediate logging");// produces output đầu ra in this order:// immediate logging// asynchronous logging has val: 777

Incumbent settings object tracking

A settings object is an environment that provides additional information when JavaScript code is running. This includes the realm và module map, as well as HTML specific information such as the origin. The incumbent settings object is tracked in order to ensure that the browser knows which one lớn use for a given piece of user code.

To better picture this, we can take a closer look at how the realm might be an issue. A realm can be roughly thought of as the global object. What is chất lượng about realms is that they hold all of the necessary information khổng lồ run JavaScript code. This includes objects like Array và Error. Each settings object has its own "copy" of these & they are not shared. That can cause some unexpected behavior in relation lớn promises. In order to get around this, we track something called the incumbent settings object. This represents information specific khổng lồ the context of the user code responsible for a certain function call.

To illustrate this a bit further we can take a look at how an

Loading an image with XHR

Another simple example using Promise and XMLHttpRequest to lớn load an image is available at the MDN GitHub js-examples repository. You can also see it in action. Each step is commented on and allows you lớn follow the Promise & XHR architecture closely.


ECMAScript Language Specification # sec-promise-objects

Browser compatibility

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript khổng lồ view data.