Promise.race() in javascript

Promise.race():  Yes, there exists a function called Promise.race() ,if you have never heard of or never used it before, lets try to understand what Promise.race() actually is ?

   Promise.race() accepts a iterable Promises and returns a new Promise which resolves as soon as one of the Promises passed to it resolves. The returned Promise will contain a value for the first Promise that got resolved. Lets understand it thorough few examples.

Example 1 :

var promise1 = Promise.resolve('a');
var promise2 = Promise.resolve('b');
var resolvedPromise = Promise.race([promise1,promise2]);
resolvedPromise.then((data) => {
  console.log('Resolved Promise data: ', data); // This prints ['a'];
});

In the above code promise1 resolved first and hence the resultant promise has value a passed to it. Its used during race conditions where any one of the promises resolves then return it.

Example 2 :

var promise1 = new Promise(function(resolve, reject) { 
                 setTimeout(resolve, 500, 'a');
              });
var promise2 = new Promise(function(resolve, reject) { 
               setTimeout(resolve, 800, 'b');
   });
var resolvedPromise = Promise.race([promise1,promise2]);
resolvedPromise.then((data) => {
  console.log('Resolved Promise data: ', data); // This prints ['a'];
});

In the above example the promise 1 and promise 2 resolves after setTimeout asynchronously. Hence, based on the time promise1 resolves first because of the 500ms compared to promise2 which resolves after 800ms. Therefore the Promise.race() will give back a promise that will contain data of promise1 i.e value 'a'. 

Now, you know how to use Promise.race() function use it wisely :).

 

 

Advertisements

Promise.all() in javascript.

You might have heard or used Promise.resolve() and Promise.reject() all the time but there is one more method of Promise that you may have rarely used. That is Promise.all() .We will see how to use this method  of Promise and few examples related to this method.

Promise.all() :

This method accepts iterable object of promises and resolves all the promises. The returned promise has an array containing all the values of the resolved promises that is passed.

If any of the iterable promise is rejected then the Promise.all() rejects otherwise it fulfills all the promises and returns an array.

Lets look at few examples of Promise.all() and understand it better.

Example 1 :

var promise1 = Promise.resolve('a');
var promise2 = Promise.resolve('b');
var resolvedPromise = Promise.all([promise1,promise2]);
resolvedPromise.then((data) => {
  console.log(data); // This prints ['a','b'];
});

The above example is one way of using the Promise.all(). It takes array of 2 promises promise1 and promise2 and resolves both and returns a new promise. If you print the data returned by the Promise.all() you will see an array which contains the values resolved by promise1 and promise2. In the above example values ['a','b'] is printed.

Example 2 :

var promise1 = Promise.resolve('a');
var promise2 = Promise.reject('b');
var resolvedPromise = Promise.all([promise1,promise2]);
resolvedPromise.then((data) => {
  console.log(data);  // It never gets resolved and hence this is not printed
}).catch((error) => {
  console.log(error); // Prints value b. Which is rejected by promise2
});

In the above example Promise.all() took an array of promises where one resolves and other rejects.  Promise.all() always rejects if one of the promise that is passed gets rejected.

You need to be careful while using Promise.all(). It needs to be used in a context where you need to show an error if any of the promise rejects. This is not the case always during application development. You don want to see error everywhere in the page just because one of the promise got rejected.

Example 3 :

var promise1 = Promise.resolve('a');
var resolvedPromise = Promise.all([promise1,'b']); // Passing a non promise value
resolvedPromise.then((data) => {
  console.log(data);  // Prints a,b
})

In the above example we passed the non promise value to Promise.all(). We just passed character 'b' to the Promise.all() function. The value will be just added to the resolved promise and still be present in the array. Usually the value is ignored and its not evaluated but its returned in the Promise rather than omitting it.

let, const and var in javascript

ECMAScript 6 introduced let and const to the javascript engine. So, lets see what is the real difference between let ,const and var. 

For video check the youtube link here : let and var in js

var and let :

var is used for global declaration and its scoped to the nearest function block.

Eg 1 :

var a = 10; // its a global declaration and its available everywhere.

Eg 2 :

function mytest() {
  var a= 10;
  if(a==10){
    var a =20;  // its the same variable a that is being modified
    console.log(a); // prints 20
  }
  console.log(a); // prints 20 here too because the 
                  //value a is scoped to nearest function mytest.
}

Eg 3: Lets consider this function. And guess the output of the below function.

function mytest() {
  for(var i=0; i<5 ;i++){
   setTimeout(function() {
    console.log(i); // what is the result of this?
   },100);
  }
}

You would expect the result to be 0, 1, 2, 3, 4 but if you run this program the result you would see is 5, 5, 5, 5, 5.  The reason behind this is same , the var is functionally scoped and not to the nearest enclosing block. So, there is only one instance of i and the same reference is modified each time.

Eg 4:

function mytest() {
 if(true) {
   var a =20;
 }
 console.log(a); // prints 20. Though a is defined inside if block the 
                 //variable a is confined to mytest block.
}

let : let is scoped to the nearest enclosing block i.e within the brackets { } it's defined in.

lets see few examples here.

Eg 1 :

let a = 10; // its similar to var when defined globally and available everwhere.

Eg 2 :

function mytest() {
  let a= 10;
  if(a==10){
    let a =20;  // its the new instance
    console.log(a); // prints 20 a is scoped to nearest block i.e if block
  }
  console.log(a); // unlike var it value a prints 10 
                  //value a is scoped to nearest block i.e mytest block
}

Eg 3:

function mytest() {
  for(let i=0; i<5 ;i++){
   setTimeout(function() {
    console.log(i); // what is the result of this?
   },100);
  }
}

The result of the above function is 0,1,2,3,4 unlike var which print 5,5,5,5,5.

Eg 4:

function mytest() {
 if(true) {
   let a =20;
 }
 console.log(a); // undefined will be printed since the 
                 // value of a is confined to just the if block.
}

Now you know the major difference between var and let. Its recommended to use let because its helpful for garbage collection so that the variables which goes out of scope can be cleaned up. In case of var the variable is always available until you close the window and the space is not cleaned up for other processes.

Const :

  • Const as the name suggests its used to initialise a  constant.
  • Once declared its value cannot be changed.
  • Const always requires an initialiser.
  • Like let const is scoped to its nearest enclosing block.

Lets take a look at few examples.

Eg 1 :

const a; // This is an invalid declaration as there is no initialiser.
const a = 10; // this is a valid declaration and if declared outside 
              // its global declaration and its value cannot be changed.

Eg 2 :

 
function mytest() {
 const a= 10;
 if(a==10){
   const a = 20; // its the new instance
   console.log(a); // prints 20 , a is scoped to nearest block i.e if block
 }
 console.log(a); //  prints 10.
}

Eg 3 :

 
function mytest() {
 const a= 10;
 a = 20; // Throws an error saying a is read only. 
         //The value cannot be changed once initialised.
}