
new Promise( /* executor */ function(resolve, reject) { ... } ); executor here. This function takes two parameters, resolve and reject , which, in turn, are also functions. Promises are usually used to perform asynchronous operations or code that can block the main thread, for example, one that works with files, makes certain API calls, queries database, deals with input / output operations, and so on. Running such asynchronous operations is performed in the executor function. If the asynchronous operation completes successfully, then the result expected from promise will be returned by calling the function resolve . The situation in which this function is called is determined by the creator of the promise. Similarly, when an error occurs, information about what happened is returned by calling the reject function. var keepsHisWord; keepsHisWord = true; promise1 = new Promise(function(resolve, reject) { if (keepsHisWord) { resolve("The man likes to keep his word"); } else { reject("The man doesnt want to keep his word"); } }); console.log(promise1); 
setTimeout function. promise2 = new Promise(function(resolve, reject) { setTimeout(function() { resolve({ message: "The man likes to keep his word", code: "aManKeepsHisWord" }); }, 10 * 1000); }); console.log(promise2); 
PromiseStatus and PromiseValue will be updated accordingly. As you can see, in this example we have changed the function that is called upon successful resolution of the promise, now it returns not an ordinary string, but an object. This is done in order to demonstrate the ability to return complex functions of data structures using the function resolve .
keepsHisWord = false; promise3 = new Promise(function(resolve, reject) { if (keepsHisWord) { resolve("The man likes to keep his word"); } else { reject("The man doesn't want to keep his word"); } }); console.log(promise3); 
PromiseStatus : pending (waiting), resolved (successful resolution) and rejected (deviation). When the promise is created, the value of pending will be in PromiseStatus , and in PromiseValue will be undefined . These values ​​will be maintained until permission or rejection of promis. When the promise is resolved or rejected , it is called the settled promise. Such a promise has moved from the waiting state to the state in which it has either a resolved state or a rejected state.Promise .Promise object is the result of the successful or unsuccessful completion of an asynchronous operation.Promise object has static methods and object prototype methods. Static methods can be called without creating an object instance, and to call prototype methods you need an instance of a Promise object. Note that both static and normal methods return Promise objects. It simplifies the work.Promise . There are three such methods. Do not forget that these methods can be called on an instance of a Promise object, and that they return promises. Thanks to all these methods, you can designate handlers that respond to changes in the state of promises. As we have seen, when a promise is created, it is in a pending state. When promise goes into the resolved or rejected state, at least one of the following methods will be invoked: Promise.prototype.catch(onRejected) Promise.prototype.then(onFulfilled, onRejected) Promise.prototype.finally(onFinally) .catch .then and .catch . Since these methods return Promise objects, their calls can be chained, this is also reflected in the diagram. If the promis provides for the use of the .finally method, it will be called when the promise becomes settled , regardless of whether the promise was successfully resolved or rejected.
var momsPromise = new Promise(function(resolve, reject) { momsSavings = 20000; priceOfPhone = 60000; if (momsSavings > priceOfPhone) { resolve({ brand: "iphone", model: "6s" }); } else { reject("We donot have enough savings. Let us save some more money."); } }); momsPromise.then(function(value) { console.log("Hurray I got this phone as a gift ", JSON.stringify(value)); }); momsPromise.catch(function(reason) { console.log("Mom coudn't buy me the phone because ", reason); }); momsPromise.finally(function() { console.log( "Irrespecitve of whether my mom can buy me a phone or not, I still love her" ); }); 
momsSavings variable to 200,000, then mom can buy a gift for her son. In this case, the above code will output the following.
.then and .catch ..then method can be assigned both the onFulfilled handler, called when the promise is successfully resolved, and the onRejected handler, called when the promise is rejected, instead of using both the .then method and the .catch method, we can achieve the same effect with only one method .then . Here is what it might look like: momsPromise.then( function(value) { console.log("Hurray I got this phone as a gift ", JSON.stringify(value)); }, function(reason) { console.log("Mom coudn't buy me the phone because ", reason); } ); .then , to use the methods .then and .catch .x and y . This is the function. function getRandomNumber(start = 1, end = 10) { //, start end >=1 end > start return parseInt(Math.random() * end) % (end-start+1) + start; } promiseTRRARNOSG call it promiseTRRARNOSG . The name of this function is decoded as promiseThatResolvesRandomlyAfterRandomNumnberOfSecondsGenerator , that is, it is a generator of promises that are randomly allowed or rejected in a random number of seconds. This function will create a promise that will be allowed or rejected after a random time interval between 2 and 10 seconds. In order to randomly resolve or reject the promise, we get a random number between 1 and 10. If this number is greater than 5, the promise will be allowed, if not, it is rejected. function getRandomNumber(start = 1, end = 10) { //, start end >=1 end > start return (parseInt(Math.random() * end) % (end - start + 1)) + start; } var promiseTRRARNOSG = (promiseThatResolvesRandomlyAfterRandomNumnberOfSecondsGenerator = function() { return new Promise(function(resolve, reject) { let randomNumberOfSeconds = getRandomNumber(2, 10); setTimeout(function() { let randomiseResolving = getRandomNumber(1, 10); if (randomiseResolving > 5) { resolve({ randomNumberOfSeconds: randomNumberOfSeconds, randomiseResolving: randomiseResolving }); } else { reject({ randomNumberOfSeconds: randomNumberOfSeconds, randomiseResolving: randomiseResolving }); } }, randomNumberOfSeconds * 1000); }); }); var testProimse = promiseTRRARNOSG(); testProimse.then(function(value) { console.log("Value when promise is resolved : ", value); }); testProimse.catch(function(reason) { console.log("Reason when promise is rejected : ", reason); }); // , . , - . for (i=1; i<=10; i++) { let promise = promiseTRRARNOSG(); promise.then(function(value) { console.log("Value when promise is resolved : ", value); }); promise.catch(function(reason) { console.log("Reason when promise is rejected : ", reason); }); } Promise object.Promise.reject(reason) and Promise.resolve(value) , which allow you to create, respectively, rejected and allowed promises.Promise.reject method, creating rejected promises. var promise3 = Promise.reject("Not interested"); promise3.then(function(value){ console.log("This will not run as it is a rejected promise. The resolved value is ", value); }); promise3.catch(function(reason){ console.log("This run as it is a rejected promise. The reason is ", reason); }); Promise.resolve method, which creates successfully resolved promises. var promise4 = Promise.resolve(1); promise4.then(function(value){ console.log("This will run as it is a resovled promise. The resolved value is ", value); }); promise4.catch(function(reason){ console.log("This will not run as it is a resolved promise", reason); }); var promise4 = Promise.resolve(1); promise4.then(function(value){ console.log("This will run as it is a resovled promise. The resolved value is ", value); }); promise4.then(function(value){ console.log("This will also run as multiple handlers can be added. Printing twice the resolved value which is ", value * 2); }); promise4.catch(function(reason){ console.log("This will not run as it is a resolved promise", reason); }); 
Promise.all and Promise.race , are designed to work with promise sets. If, to solve a problem, you need to process several promises, it is most convenient to put these promises in an array and then perform the necessary actions with them. In order to understand the essence of the methods considered here, we will not be able to use our convenient function promiseTRRARNOSG , since the result of its work depends too much on the will of the case. It will be more convenient for us to take advantage of something that produces more predictable promises, which will allow us to understand their behavior. Therefore, we will create two new functions. One of them ( promiseTRSANSG ) will create promises that are resolved after n seconds, the second ( promiseTRSANSG ) will create promises that are rejected after n seconds. var promiseTRSANSG = (promiseThatResolvesAfterNSecondsGenerator = function( n = 0 ) { return new Promise(function(resolve, reject) { setTimeout(function() { resolve({ resolvedAfterNSeconds: n }); }, n * 1000); }); }); var promiseTRJANSG = (promiseThatRejectsAfterNSecondsGenerator = function( n = 0 ) { return new Promise(function(resolve, reject) { setTimeout(function() { reject({ rejectedAfterNSeconds: n }); }, n * 1000); }); }); Promise.all method.Promise.all(iterable) method returns a promise that will be resolved when all promises that are passed as an iterable argument are iterable , or when this argument does not contain promises. This promise will be rejected if any of the transmitted promises are rejected. console.time("Promise.All"); var promisesArray = []; promisesArray.push(promiseTRSANSG(1)); promisesArray.push(promiseTRSANSG(4)); promisesArray.push(promiseTRSANSG(2)); var handleAllPromises = Promise.all(promisesArray); handleAllPromises.then(function(values) { console.timeEnd("Promise.All"); console.log("All the promises are resolved", values); }); handleAllPromises.catch(function(reason) { console.log("One of the promises failed with the following reason", reason); }); 
Promise.all instruction. console.time("Promise.All"); var promisesArray = []; promisesArray.push(1); promisesArray.push(4); promisesArray.push(2); var handleAllPromises = Promise.all(promisesArray); handleAllPromises.then(function(values) { console.timeEnd("Promise.All"); console.log("All the promises are resolved", values); }); handleAllPromises.catch(function(reason) { console.log("One of the promises failed with the following reason", reason); }); 
Promise.all almost instantly resolved.Promise.all is rejected. console.time("Promise.All"); var promisesArray = []; promisesArray.push(promiseTRSANSG(1)); promisesArray.push(promiseTRSANSG(5)); promisesArray.push(promiseTRSANSG(3)); promisesArray.push(promiseTRJANSG(2)); promisesArray.push(promiseTRSANSG(4)); var handleAllPromises = Promise.all(promisesArray); handleAllPromises.then(function(values) { console.timeEnd("Promise.All"); console.log("All the promises are resolved", values); }); handleAllPromises.catch(function(reason) { console.timeEnd("Promise.All"); console.log("One of the promises failed with the following reason ", reason); }); Promise.all stops after the first rejected promise with a message that gives this promise.
Promise.race(iterable) method returns the allowed or rejected promis with the value or cause of the rejection, after one of the transmitted promises is, respectively, allowed or rejected.Promise.race .Promise.race is resolved before anyone else. console.time("Promise.race"); var promisesArray = []; promisesArray.push(promiseTRSANSG(4)); promisesArray.push(promiseTRSANSG(3)); promisesArray.push(promiseTRSANSG(2)); promisesArray.push(promiseTRJANSG(3)); promisesArray.push(promiseTRSANSG(4)); var promisesRace = Promise.race(promisesArray); promisesRace.then(function(values) { console.timeEnd("Promise.race"); console.log("The fasted promise resolved", values); }); promisesRace.catch(function(reason) { console.timeEnd("Promise.race"); console.log("The fastest promise rejected with the following reason ", reason); }); 
Promise.race is resolved.Promise.race is rejected. console.time("Promise.race"); var promisesArray = []; promisesArray.push(promiseTRSANSG(4)); promisesArray.push(promiseTRSANSG(6)); promisesArray.push(promiseTRSANSG(5)); promisesArray.push(promiseTRJANSG(3)); promisesArray.push(promiseTRSANSG(4)); var promisesRace = Promise.race(promisesArray); promisesRace.then(function(values) { console.timeEnd("Promise.race"); console.log("The fasted promise resolved", values); }); promisesRace.catch(function(reason) { console.timeEnd("Promise.race"); console.log("The fastest promise rejected with the following reason ", reason); }); 
Promise.race is rejected.promiseTRJANSG , promiseTRSANSG and promiseTRRARNOSG to simulate a number of promise usage scenarios that will allow you to better understand them. In addition, note that using the console.time command allows you to figure out the time it takes to execute a certain piece of code, and, for example, find out whether promises are performed in parallel or sequentially. Here is the link to the gist page with the code. And by the way, if you like, take a look at the Bluebird library, which contains some interesting methods for working with promises..then method, for those cases when the promise is rejected, use the .catch ..then and .catch in all promises..finally method.Promise , , , .Promise.all , .Source: https://habr.com/ru/post/418085/
All Articles