Search code examples
javascriptreactjsecmascript-6es6-promisees6-class

How to show value from 2 promises in a single line?


I have a class with static methods returning promises. I am able to print in console the values returned by these promises in seperate lines. But I want to print in console in one line the weather and currency for a given city (say London). The output should be like this:

 The weather of London is cloudy. The local currency of London is GBP.

I am unable to do it with nested promises too. How it should be done?

Here is the code:

    class Provider{
            static getWeather(city){
            return Promise.resolve(`The weather of ${city} is cloudy.`);
            }
            static getLocalCurrency(city){
            return Promise.resolve(`The local currency of ${city} is GBP`)
            }
         };

    Provider.getWeather(value).then((value)=> console.log(value));
    Provider.getLocalCurrency("London").then((value)=> console.log(value));   


    

Solution

  • You can use Promise.all.

    class Provider {
      static getWeather(city) {
        return Promise.resolve(`The weather of ${city} is cloudy.`);
      }
      static getLocalCurrency(city) {
        return Promise.resolve(`The local currency of ${city} is GBP`);
      }
    }
    
    Promise.all([
      Provider.getWeather("london"),
      Provider.getLocalCurrency("London")
    ]).then(([weather, currency]) => {
      console.log(`${weather} ${currency}`);
    });