How to chain JS promises?

Many times we have promises which needs to be executed one by one and may have data dependency from the previous promise. For example, we want to write three promises where one provides current date, second one provides date in milliseconds and third one provides the formatted date in YYYY-MM-DD format.

There can be more than one way to execute this code. Here I will describe two ways, you can chain these promises.

1. We can chain multiple promises using then

const getCurrentDate = ()=>{
	return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(new Date());
        }, 2000);
   });
}

async function getCurrentDateInMilliSeconds(date) {
  return date.getTime();
}

const getDateInFormat = (dateInMilliseconds) =>{
  const date = new Date(dateInMilliseconds)
  return [date.getFullYear(),("0" + (date.getMonth()+1)).slice(-2),("0"+ date.getDate()).slice(-2)].join('-');
}

getCurrentDate().then(getCurrentDateInMilliSeconds).then(getDateInFormat).then(res =>{
  console.log(res)
})

2. Make use of async / await – this is now supported in node v8.X and up versions.

async function getDateData()  {
   try{
    const currentDate= await getCurrentDate();
    const currentDateInTimesStamp = await getCurrentDateInMilliSeconds(currentDate);
    const currentDateFormat = await getDateInFormat(currentDate)
    return [currentDate,currentDateInTimesStamp,currentDateFormat];
   }catch(e){
     console.log(e)
   }    
}

const getCurrentDate = ()=>{
   return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(new Date());
        }, 2000);
   });
}

const getCurrentDateInMilliSeconds = (date) =>{
  return date.getTime();
}

const getDateInFormat = (date) =>{
  return [date.getFullYear(),("0" + (date.getMonth()+1)).slice(-2),("0"+ date.getDate()).slice(-2)].join('-');
}

getDateData().then(res => {
  console.log(res) //Provies the array with currentDate, dateInmilliseconds and formatted Date
}).catch(error =>{
  console.log(error)
})

Both ways are accepted practice, so you can use either one of them for developing your application. aysnc/await looks neat and gives readable code. It helps in overall performance and responsiveness of your application. It is also easier to maintain the code written in async/ await.

I hope this post was helpful to you. If you like my post, follow me @twitter/andramazo.

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top