Thursday, 8 March 2018

Example of Promises in javascript

Exp- 1

var promisesToCleanRoom = new Promise(function(resolve, reject){

//login for cleaning room

var IsRoomCleaned = false;

  if(IsRoomCleaned){
     resolve('clean');
  }
  else{
   reject('not clean');
  }
});

promisesToCleanRoom.then(function(fromResolve){
  console.log('Room is' + fromResolve);  //Room is clean
}).catch(function(fromReject){
 console.log('Room is ' +fromReject);   //Room is not clean
});

Exp- 2

let cleanRoom = function(){
    return new Promise(function(resolve, reject){
        resolve('Cleaned the room.')
    });
}

let removeGarbage = function(message){
    return new Promise(function(resolve, reject){
        resolve(message + 'Removed garbage.')
    });
}

let winIceCream = function(message){
    return new Promise(function(resolve, reject){
        resolve(message + 'You won icecream.')
    });
}

//to handle nested promises objects
//Case-1

cleanRoom().then(function(result){
    return removeGarbage(result);
}).then(function(result){
   return winIceCream(result);
}).then(function(result){
   console.log('finished!!'+ result );
});

//Case-2 if all of the function executes successfully then it executes call back function

Promise.all([cleanRoom(),removeGarbage(),winIceCream()]).then(function(){
  console.log('all finished!!');
})

//Case-3 any one of the function executes successfully then it executes call back function

Promise.race([cleanRoom(),removeGarbage(),winIceCream()]).then(function(){
  console.log('one of them is finished!!');
})



No comments:

Post a Comment