Skip to main content

Promise - deferred and asynchronous computation

@serverSerrverlesskiy

A Promise is an object that contains the future value of an asynchronous operation. For example, if you request some data from a server, a promise promises us to receive this data that we can use in the future.

math

At first, the promise has the status pending, then it has one of: fulfilled ("successfully completed") or rejected (" completed with an error๐Ÿ™…โ€โ™‚๏ธ ").

promise states

  1. Pending - The promise is pending if the result is not ready. That is, it is waiting for something to complete (for example, the completion of an asynchronous operation).
  2. Fulfilled - Promise resolved if result is available. That is, something completed its execution (for example, an asynchronous operation) and everything went well.
  3. Rejected - Promise was rejected if an error occurred during execution.

Create a promise#

Plus

A Promise object is created using the new keyword and its own constructor. The Promise constructor takes one argument, a callback, also known as an execution functionโš™๏ธ, which takes 2 callbacks, resolve and reject.

The executive function is executed immediately after the promise is created. A promise is made fulfilled by calling resolve and rejected by calling reject.

const promise = new Promise((resolve, reject) => {
if (allWentWell) {
resolve('Everything went great!')
} else {
reject('Something went wrong')
}
})

resolve and reject take one argument, which can be a string, number, boolean expression, array, or object.

To provide a function with promises functionality, you just need to return a Promise object in it:

function myAsyncFunction(url) {
return new Promise((resolve, reject) => {
// function code
})
}

Payment#

Now you are on a stripped-down version of the site, after subscribing to Patreon, you will get full access to the training course, as well as access to our server's private channels in Discord.

Download our mobile application or get tested in our JavaScript telegram bot, and also subscribe to our news.

Become a Patron!

Sumerian school

Contributors โœจ#

Thanks goes to these wonderful people (emoji key):


Philipp Dvinyaninov

๐Ÿ“–

Dmitriy Vasilev

๐Ÿ’ต

Resoner2005

๐Ÿ› ๐ŸŽจ ๐Ÿ–‹

Navernoss

๐Ÿ–‹ ๐Ÿ› ๐ŸŽจ

Become a Patron!