How do we implement the below code using Promise.all() ? I have tried using promise,async/await way. But, this problem requires something to be done using Promise.all()
class Provider{
/*
Gets the weather for a given city
*/
static getWeather(city){
return Promise.resolve(`The weather of ${city} is cloudy`)
};
/*
Gets the weather for a given city
*/
static getLocalCurrency(city){
return Promise.resolve(`The local currency of ${city} is GBP`)
};
/*
Gets the Longitude and Latitude, this function returns a city
*/
static findCity(long,lat){
return Promise.resolve(`London`)
};
};
//my implamentation;
let fnCall = async () => {
let city = await Provider.findCity(0.1278,51.5074);
let cityWeather = await Provider.getWeather(city);
let cityCurrency = await Provider.getLocalCurrency(city);
console.log(city);
console.log(cityWeather);
console.log(cityCurrency);
}
fnCall();
CodePudding user response:
You can't do Promise.all
from the outset because the 2nd and 3rd are dependent on the first. But you can still chain them, using Promise.all
on the inner, and passing the city result to the end of the chain.
let fnCall = async () => {
return await Provider
.findCity(0.1278,51.5074)
.then(city => {
return Promise.all([
city,
Provider.getWeather(city),
Provider.getLocalCurrency(city)
])
.then(([city, weather, currency]) => {
console.log(city);
console.log(weather);
console.log(currency);
})
}
fnCall();
CodePudding user response:
The idea is to serially chain the dependant API calls , (output of one is input to next) and streamline/pipe the independent calls parallelly.
Rest if you're interested to stick to async await sugar-coated syntax , see below snippet example.
class Provider{
/*
Gets the weather for a given city
*/
static getWeather(city){
return Promise.resolve(`The weather of ${city} is cloudy`)
};
/*
Gets the weather for a given city
*/
static getLocalCurrency(city){
return Promise.resolve(`The local currency of ${city} is GBP`)
};
/*
Gets the Longitude and Latitude, this function returns a city
*/
static findCity(long,lat){
return Promise.resolve(`London`)
};
};
let fnCall = async () => {
let city = await Provider.findCity(0.1278,51.5074);
let [cityWeather, cityCurrency] = await Promise.all([Provider.getWeather(city),Provider.getLocalCurrency(city)]);
console.log(city);
console.log(cityWeather);
console.log(cityCurrency);
}
fnCall();