Understanding JavaScript Promise Object

I am trying to wrap my head around a promise object in JavaScript. So, I have this little piece of code. I have a promise object and two console.log() on either side of the promise object. I thought it would print

Hello

There

3

but printed

 HI zami there 

Why is this so? I don't understand how a promise works, but I understand how an asynchronous callback works in JavaScript. Can anyone shed some light on this subject?

 console.log('hi'); var myPromise = new Promise(function (resolve, reject) { if (true) { resolve('There!'); } else { reject('Aww, didn\'t work.'); } }); myPromise.then(function (result) { // Resolve callback. console.log(result); }, function (result) { // Reject callback. console.error(result); }); console.log('zami'); 
+16
source share
4 answers

Keeping promises is asynchronous, which means it is executed, but the program will not wait until it finishes to continue working with the rest of the code.

Basically, your code does the following:

  • Hello Magazine
  • Create a promise
  • Keeping a promise
  • Zami magazine
  • The promise is permitted and recorded there.

If you want it to print "Hello, zami", you need to

 myPromise.then(function (result) { // Resolve callback. console.log(result); console.log('zami'); }, function (result) { // Reject callback. console.error(result); }); 
+16
source

Summary:

A promise in Javascript is an object that represents the possible completion or failure of an asynchronous operation. Promises are proxies for the value that will be reached at some point in the future.

A promise can have 3 states:

  1. Waiting . This is the initial state of promise. Now the promise is awaiting approval or rejection . For example, when you access the Internet using an AJAX request and make a request in a promise. Then the promise will be delayed in a time window in which the request will not be returned.
  2. Completed: When the operation is completed successfully, the promise is fulfilled. For example, when we strive to be online, using AJAX for some JSON data and wrapping them in a promise. When we successfully receive data, the promise is considered fulfilled.
  3. Rejected: If the operation fails, the promise is rejected. For example, when we strive to be online, using AJAX for some JSON data and wrapping them in a promise. When we get 404 error, the promise was rejected.

Constructor Promise:

We can create a promise as follows:

 let prom = new Promise((res, rej) => { console.log('synchronously executed'); if (Math.random() > 0.5) { res('Success'); } else { rej('Error'); } }) prom.then((val) => { console.log('asynchronously executed: ' + val); }).catch((err) => { console.log('asynchronously executed: ' + err); }).finally(() => { console.log('promise done executing'); }); console.log('last log'); 

Sights:

  • The code inside the promise constructor runs synchronously .
  • The then method takes a callback as the first argument, which is executed asynchronously when the promise is fulfilled.
  • The then method takes a callback as the second argument, which is executed asynchronously when the promise is rejected. However, for this we usually use the catch method (because it is more verbose), which also accepts a callback that runs asynchronously when the promise is rejected. catch is essentially the same as then(null, failCallback) .
  • The then callback receives the allowed value as the first argument (in this case, the string "success").
  • The catch callback receives the rejected value rejected value (in this case, the string "Error") as the first argument.
  • The finally method receives a callback that is executed both when the promise is fulfilled and when it is rejected. Here we can write the "cleanup" code, which should always be executed, regardless of the result of the promise.

Your example:

In your code, โ€œZamiโ€ was printed before โ€œthere,โ€ because the log that wrote โ€œthereโ€ was in the then callback function. We indicated earlier that these callbacks are executed asynchronously and therefore will be executed last.

+8
source

Even if you have resolved the promise synchronously, the handlers you pass to then are called asynchronously. This conforms to a specific specification :

onFulfilled and onRejected are executed asynchronously after the rotation of the event loop, which is then called, and with a new stack

+5
source

If you want to know how it works, you can read it here . It shows an example of how to fulfill a promise so that you can better understand the object.

+1
source

All Articles