Return promise object that should be resolved with value that is

Return promise object that should be resolved with value that is

Promise

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

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

Description

A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to 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 to supply the value at some point in the future.

A Promise is in one of these states:

The eventual state of a pending promise can either be fulfilled with a value or rejected with a reason (error). When either of these options occur, 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.

A promise is said to be settled if it is either fulfilled or rejected, but not pending.

Return promise object that should be resolved with value that is. Смотреть фото Return promise object that should be resolved with value that is. Смотреть картинку Return promise object that should be resolved with value that is. Картинка про Return promise object that should be resolved with value that is. Фото Return promise object that should be resolved with value that is

You will also hear the term resolved used with promises — this means that the promise is settled or «locked-in» to match the eventual state of another promise, and further resolving or rejecting it has no effect. The States and fates document from the original Promise proposal contains more details about promise terminology. Colloquially, «resolved» promises are often equivalent to «fulfilled» promises, but as illustrated in «States and fates», resolved promises can be pending or rejected as well. For example:

This promise is already resolved at the time when it’s created (because the resolveOuter is called synchronously), but it is resolved with another promise, and therefore won’t be fulfilled until 1 second later, when the inner promise fulfills. In practice, the «resolution» is often done behind the scenes and not observable, and only its fulfillment or rejection are.

Note: Several other languages have mechanisms for lazy evaluation and deferring a computation, which they also call «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 lazily evaluate an expression, consider using a function with no arguments e.g. f = () => expression to create the lazily-evaluated expression, and f() to evaluate the expression immediately.

Chained Promises

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

Note: For faster execution, all synchronous actions should preferably be done within one handler, otherwise it would take several ticks to execute all handlers in sequence.

The promises of a chain are nested like Russian dolls, but get popped like the top of a stack. The first promise in the chain is most deeply nested and is the first to pop.

Thenables

To interoperate with the existing Promise implementations, the language allows using thenables in place of promises. For example, Promise.resolve will not only resolve promises, but also trace thenables.

Incumbent settings object tracking

A settings object is an environment that provides additional information when JavaScript code is running. This includes the realm and 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 to use for a given piece of user code.

To illustrate this a bit further we can take a look at how an embedded in a document communicates with its host. Since all web APIs are aware of the incumbent settings object, the following will work in all browsers:

The same concept applies to promises. If we modify the above example a little bit, we get this:

If we change this so that the in the document is listening to post messages, we can observe the effect of the incumbent settings object:

In the above example, the inner text of the will be updated only if the incumbent settings object is tracked. This is because without tracking the incumbent, we may end up using the wrong environment to send the message.

Note: Currently, incumbent realm tracking is fully implemented in Firefox, and has partial implementations in Chrome and Safari.

Constructor

Creates a new Promise object. The constructor is primarily used to wrap functions that do not already support promises.

Static methods

Wait for all promises to be fulfilled, or for any to be rejected.

If the returned promise fulfills, it is fulfilled with an aggregating array of the values from the fulfilled promises, in the same order as defined in the iterable of multiple promises.

If it rejects, it is rejected with the reason from the first promise in the iterable that was rejected.

Wait until all promises have settled (each may fulfill or reject).

Returns a Promise that fulfills after all of the given promises is either fulfilled or rejected, with an array of objects that each describe the outcome of each promise.

Takes an iterable of Promise objects and, as soon as one of the promises in the iterable fulfills, returns a single promise that fulfills with the value from that promise.

Wait until any of the promises is fulfilled or rejected.

If the returned promise fulfills, it is fulfilled with the value of the first promise in the iterable that fulfilled.

If it rejects, it is rejected with the reason from the first promise that was rejected.

Returns a new Promise object that is rejected with the given reason.

Returns a new Promise object that is resolved with the given value. If the value is a thenable (i.e. has a then method), the returned promise will «follow» that thenable, adopting its eventual state; otherwise, the returned promise will be fulfilled with the value.

Generally, if you don’t know if a value is a promise or not, Promise.resolve(value) it instead and work with the return value as a promise.

Instance methods

See the Microtask guide to learn more about how these methods use the Microtask queue and services.

Appends a rejection handler callback to the promise, and returns a new promise resolving to the return value of the callback if it is called, or to its original fulfillment value if the promise is instead fulfilled.

Appends fulfillment and rejection handlers to the promise, and returns a new promise resolving to the return value of the called handler, or to its original settled value if the promise was not handled (i.e. if the relevant handler onFulfilled or onRejected is not a function).

Appends a handler to the promise, and returns a new promise that is resolved when the original promise is resolved. The handler is called when the promise is settled, whether fulfilled or rejected.

Examples

Basic Example

Example with diverse situations

The example function tetheredGetNumber() shows that a promise generator will utilize reject() while setting up an asynchronous call, or within the call-back, or both. The function promiseGetWord() illustrates how an API function might generate and return a promise in a self-contained manner.

This code can be run under NodeJS. Comprehension is enhanced by seeing the errors actually occur. To force more errors, change the threshold values.

Advanced Example

By clicking the button several times in a short amount of time, you’ll even see the different promises being fulfilled one after another.

JavaScript

Result

Loading an image with XHR

Another simple example using Promise and XMLHttpRequest to 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 to follow the Promise and XHR architecture closely.

JavaScript Promise.resolve: The Complete Guide

Return promise object that should be resolved with value that is. Смотреть фото Return promise object that should be resolved with value that is. Смотреть картинку Return promise object that should be resolved with value that is. Картинка про Return promise object that should be resolved with value that is. Фото Return promise object that should be resolved with value that is

The promise is the JavaScript object that links a “producing code” and the “consuming code” together. In regular terms, this is the “subscription list”. It is like the producers’ and consumers’ concepts.

Javascript promise.resolve()

JavaScript Promise.resolve() is a built-in function that returns the Promise object resolved with the given value. If the value is the promise, that promise is returned; if the value is a thenable(i.e., has a “then” method), then the returned promise will “follow” that thenable, adopting its eventual state; otherwise, the returned promise will be fulfilled with the value.

The “producing code” takes whatever time it needs to produce the promised result, and a “promise” makes the result available to all subscribers when it’s ready.

If the job is finished successfully, with the result value.

Return promise object that should be resolved with value that is. Смотреть фото Return promise object that should be resolved with value that is. Смотреть картинку Return promise object that should be resolved with value that is. Картинка про Return promise object that should be resolved with value that is. Фото Return promise object that should be resolved with value that is

Syntax

The syntax for JavaScript Promise.resolve() is the following.

Parameters

This Promise resolves the value parameter. It can also be the Promise or a thenable to resolve.

The promise is resolved with the given value, or the promise passed as the value if the value was a promise object. The static Promise.resolve() function returns the resolved Promise.

Example

Let us take a simple example. First, write the following code inside the app.js file.

Save the file, go to the terminal, and run the file by typing the node app command.

Return promise object that should be resolved with value that is. Смотреть фото Return promise object that should be resolved with value that is. Смотреть картинку Return promise object that should be resolved with value that is. Картинка про Return promise object that should be resolved with value that is. Фото Return promise object that should be resolved with value that is

Here, the p1 promise is thenable and eventually returns the value AppDividend.

Resolving an array

Let us take a simple example that resolves an array.

It will return the 18 value.

Return promise object that should be resolved with value that is. Смотреть фото Return promise object that should be resolved with value that is. Смотреть картинку Return promise object that should be resolved with value that is. Картинка про Return promise object that should be resolved with value that is. Фото Return promise object that should be resolved with value that is

Resolving another Promise

Let us take the following example.

Here, we are resolving a promise inside a promise. So the final output will be the value of the first promise.

Return promise object that should be resolved with value that is. Смотреть фото Return promise object that should be resolved with value that is. Смотреть картинку Return promise object that should be resolved with value that is. Картинка про Return promise object that should be resolved with value that is. Фото Return promise object that should be resolved with value that is

Difference between Promise.resolve() and new Promise()

Syntax of Promise.resolve() is following.

that is the same as

there is a subtlety.

Promise returning functions should generally guarantee that they should not throw synchronously since they might throw asynchronously.

To prevent unexpected results and race conditions – throws are usually converted to returned rejections.

With this in mind, the promise constructor threw safely when the spec was created.

Promise.resolve() is used to cast objects and foreign promises (thenables) to promises. So that’s its use case.

Conclusion

The rule is that if a function is inside, the handler returns the value, and the promise resolves/rejects that value.

If a function returns the promise, the next, then the clause will be the then clause of a promise a function returned.

Making things special, inside a then handler function:

1) When x is the value (number, string, etc.):

2) When x is the Promise that is already settled (not pending anymore):

3) When the x is the pending Promise, return x will return a pending Promise, which will be evaluated later.

Understanding Promise.Resolve()

Javascript’s Promise resolve() is an inbuilt function that returns the Promise object that is already resolved with the given value.

If the value is the promise, that promise is returned; if the value is a thenable (i.e., has a then method), then the returned promise will “ follow” that thenable, adopting its eventual state; otherwise, the returned promise will be fulfilled with the value.

A Promise is a JavaScript object that links a “producing code” and the “consuming code” together. In regular terms, this is the “subscription list”. It is like the producers and consumers’ concept.

The “producing code” takes whatever time it needs to produce the promised result, and a “promise” makes the result available to all of the subscribers when it’s ready.

Return promise object that should be resolved with value that is. Смотреть фото Return promise object that should be resolved with value that is. Смотреть картинку Return promise object that should be resolved with value that is. Картинка про Return promise object that should be resolved with value that is. Фото Return promise object that should be resolved with value that is

The syntax for Javascript Promise.resolve() is the following.

This Promise resolves the value parameter. It can also be the Promise or a thenable to resolve. The static Promise.resolve() function returns the Promise that is resolved.

Let’s see with an example.

Here, the promiseObject promise is thenable, and it eventually returns the value “ Promise Resolved…. ”.

Resolving an array

Resolving another Promise

Here, we are resolving promise inside a promise. So the final output will be the value of the first promise: Batman.

Promise.resolve() VS new Promise()

Syntax of Promise.resolve() is following.

that is basically the same as

Promise returning functions should generally have the guarantee that they should not throw synchronously since they might throw asynchronously.

In general, Promise.resolve() is used for casting the objects and foreign promises (thenables) to promises.

Return promise object that should be resolved with value that is. Смотреть фото Return promise object that should be resolved with value that is. Смотреть картинку Return promise object that should be resolved with value that is. Картинка про Return promise object that should be resolved with value that is. Фото Return promise object that should be resolved with value that is

Conclusion

The rule is, if a function that is inside a then handler returns the value, the promise resolves/rejects with that value.

If a function returns the promise, what happens is the next “ then clause”, will be the “ then clause” of a promise, which the function returned.

Making things special, inside “ then handler” function:

When x is the value (number, string, etc):

When x is the Promise that is already settled (not pending anymore):

When the x is the Promise that is pending:

How to use promises

Promises are the foundation of asynchronous programming in modern JavaScript. A promise is an object returned by an asynchronous function, which represents the current state of the operation. At the time the promise is returned to the caller, the operation often isn’t finished, but the promise object provides methods to handle the eventual success or failure of the operation.

Prerequisites:Basic computer literacy, a reasonable understanding of JavaScript fundamentals, including event handling.
Objective:To understand how to use promises in JavaScript.

In the last article, we talked about the use of callbacks to implement asynchronous functions. With that design, you call the asynchronous function, passing in your callback function. The function returns immediately and calls your callback when the operation is finished.

With a promise-based API, the asynchronous function starts the operation and returns a Promise object. You can then attach handlers to this promise object, and these handlers will be executed when the operation has succeeded or failed.

Using the fetch() API

Note: In this article we will explore promises by copying code samples from the page into your browser’s JavaScript console. To set this up:

Copy this into your browser’s JavaScript console:

The complete output should be something like:

Note that Started request… is logged before we receive the response. Unlike a synchronous function, fetch() returns while the request is still going on, enabling our program to stay responsive. The response shows the 200 (OK) status code, meaning that our request succeeded.

This probably seems a lot like the example in the last article, where we added event handlers to the XMLHttpRequest object. Instead of that, we’re passing a handler into the then() method of the returned promise.

Chaining promises

With the fetch() API, once you get a Response object, you need to call another function to get the response data. In this case, we want to get the response data as JSON, so we would call the json() method of the Response object. It turns out that json() is also asynchronous. So this is a case where we have to call two successive asynchronous functions.

This should log «baked beans» (the name of the first product listed in «products.json»).

But wait! Remember the last article, where we said that by calling a callback inside another callback, we got successively more nested levels of code? And we said that this «callback hell» made our code hard to understand? Isn’t this just the same, only with then() calls?

It is, of course. But the elegant feature of promises is that then() itself returns a promise, which will be completed with the result of the function passed to it. This means that we can (and certainly should) rewrite the above code like this:

Before we move on to the next step, there’s one more piece to add. We need to check that the server accepted and was able to handle the request, before we try to read it. We’ll do this by checking the status code in the response and throwing an error if it wasn’t «OK»:

Catching errors

This brings us to the last piece: how do we handle errors? The fetch() API can throw an error for many reasons (for example, because there was no network connectivity or the URL was malformed in some way) and we are throwing an error ourselves if the server returned an error.

In the last article, we saw that error handling can get very difficult with nested callbacks, making us handle errors at every nesting level.

To support error handling, Promise objects provide a catch() method. This is a lot like then() : you call it and pass in a handler function. However, while the handler passed to then() is called when the asynchronous operation succeeds, the handler passed to catch() is called when the asynchronous operation fails.

If you add catch() to the end of a promise chain, then it will be called when any of the asynchronous function calls fails. So you can implement an operation as several consecutive asynchronous function calls, and have a single place to handle all errors.

Try running this version: you should see the error logged by our catch() handler.

Promise terminology

Promises come with some quite specific terminology that it’s worth getting clear about.

First, a promise can be in one of three states:

Note that what «succeeded» or «failed» means here is up to the API in question: for example, fetch() considers a request successful if the server returned an error like 404 Not Found, but not if a network error prevented the request being sent.

Sometimes, we use the term settled to cover both fulfilled and rejected.

A promise is resolved if it is settled, or if it has been «locked in» to follow the state of another promise.

The article Let’s talk about how to talk about promises gives a great explanation of the details of this terminology.

Combining multiple promises

The promise chain is what you need when your operation consists of several asynchronous functions, and you need each one to complete before starting the next one. But there are other ways you might need to combine asynchronous function calls, and the Promise API provides some helpers for them.

Sometimes, you need all the promises to be fulfilled, but they don’t depend on each other. In a case like that, it’s much more efficient to start them all off together, then be notified when they have all fulfilled. The Promise.all() method is what you need here. It takes an array of promises and returns a single promise.

The promise returned by Promise.all() is:

Here, we’re making three fetch() requests to three different URLs. If they all succeed, we will log the response status of each one. If any of them fail, then we’re logging the failure.

With the URLs we’ve provided, all the requests should be fulfilled, although for the second, the server will return 404 (Not Found) instead of 200 (OK) because the requested file does not exist. So the output should be:

If we try the same code with a badly formed URL, like this:

Then we can expect the catch() handler to run, and we should see something like:

Note that in this case we can’t predict which fetch request will complete first.

These are just two of the extra Promise functions for combining multiple promises. To learn about the rest, see the Promise reference documentation.

async and await

The async keyword gives you a simpler way to work with asynchronous promise-based code. Adding async at the start of a function makes it an async function:

Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.

This enables you to write code that uses asynchronous functions but looks like synchronous code. For example, we could use it to rewrite our fetch example:

We can even use a try. catch block for error handling, exactly as we would if the code were synchronous.

Note though that async functions always return a promise, so you can’t do something like:

Instead, you’d need to do something like:

Also, note that you can only use await inside an async function, unless your code is in a JavaScript module. That means you can’t do this in a normal script:

You’ll probably use async functions a lot where you might otherwise use promise chains, and they make working with promises much more intuitive.

Keep in mind that just like a promise chain, await forces asynchronous operations to be completed in series. This is necessary if the result of the next operation depends on the result of the last one, but if that’s not the case then something like Promise.all() will be more performant.

Conclusion

Promises are the foundation of asynchronous programming in modern JavaScript. They make it easier to express and reason about sequences of asynchronous operations without deeply nested callbacks, and they support a style of error handling that is similar to the synchronous try. catch statement.

The async and await keywords make it easier to build an operation from a series of consecutive asynchronous function calls, avoiding the need to create explicit promise chains, and allowing you to write code that looks just like synchronous code.

Promises work in the latest versions of all modern browsers; the only place where promise support will be a problem is in Opera Mini and IE11 and earlier versions.

We didn’t touch on all promise features in this article, just the most interesting and useful ones. As you start to learn more about promises, you’ll come across more features and techniques.

Many modern Web APIs are promise-based, including WebRTC, Web Audio API, Media Capture and Streams, and many more.

Promise

Imagine that you’re a top singer, and fans ask day and night for your upcoming song.

To get some relief, you promise to send it to them when it’s published. You give your fans a list. They can fill in their email addresses, so that when the song becomes available, all subscribed parties instantly receive it. And even if something goes very wrong, say, a fire in the studio, so that you can’t publish the song, they will still be notified.

Everyone is happy: you, because the people don’t crowd you anymore, and fans, because they won’t miss the song.

This is a real-life analogy for things we often have in programming:

The analogy isn’t terribly accurate, because JavaScript promises are more complex than a simple subscription list: they have additional features and limitations. But it’s fine to begin with.

The constructor syntax for a promise object is:

The function passed to new Promise is called the executor. When new Promise is created, the executor runs automatically. It contains the producing code which should eventually produce the result. In terms of the analogy above: the executor is the “singer”.

Its arguments resolve and reject are callbacks provided by JavaScript itself. Our code is only inside the executor.

When the executor obtains the result, be it soon or late, doesn’t matter, it should call one of these callbacks:

So to summarize: the executor runs automatically and attempts to perform a job. When it is finished with the attempt, it calls resolve if it was successful or reject if there was an error.

The promise object returned by the new Promise constructor has these internal properties:

So the executor eventually moves promise to one of these states:

Later we’ll see how “fans” can subscribe to these changes.

Here’s an example of a promise constructor and a simple executor function with “producing code” that takes time (via setTimeout ):

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *