如何使用Promise.all更乐观地重构此代码



我们如何使用Promise.all((实现以下代码 我尝试过使用promise、async/await方式。但是,这个问题需要使用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();

其思想是串行链接相关的API调用(一个调用的输出输入到下一个调用(,并并行地精简/管道化独立调用。

如果您有兴趣坚持使用async wait糖衣语法,请参阅下面的代码段示例。

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();

不能从一开始就执行Promise.all,因为第二个和第三个依赖于第一个。但您仍然可以将它们链接起来,在内部使用Promise.all,并将城市结果传递到链的末尾。

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();

最新更新