实现说明
全部逻辑都在函数 loadWeather、loadNews中。
await 点把异步工作排成序列,拒绝落在取结果的那一行。
使用要点
- 演示输出是带标签的(
weather:、news:),每个操作都会留下自己的一行标注。
常见问题
需要标准库之外的东西吗?
除标准库外不引入任何东西——这个示例没有依赖。 文件在加载时定义 loadWeather、loadNews。
入口签名:const loadWeather = async ()
核心语句
Promise.all([loadWeather(), loadNews()]).then(([weather, news]) => {
console.log('weather:', weather.celsius);
console.log('news:', news.headlines.join(' | '));
});
const loadNews = async (): Promise<News> => ({ headlines: ['deploy done', 'cache warm'] });
const loadWeather = async (): Promise<Weather> => ({ celsius: 21.5 });
代码示例
type Weather = { celsius: number };
type News = { headlines: string[] };
const loadWeather = async (): Promise<Weather> => ({ celsius: 21.5 });
const loadNews = async (): Promise<News> => ({ headlines: ['deploy done', 'cache warm'] });
// Promise.all 保留元组形状:解构出的 weather 是 Weather,news 是 News
Promise.all([loadWeather(), loadNews()]).then(([weather, news]) => {
console.log('weather:', weather.celsius);
console.log('news:', news.headlines.join(' | '));
});
// 三元素元组同样成立:[string, number, boolean]
Promise.all([Promise.resolve('env'), Promise.resolve(2), Promise.resolve(true)]).then(
([name, version, ready]) => {
console.log(name, version, ready);
},
);