← 中文资源

简体中文版本

Promise.all 推断元组结果类型

Promise.all 保留输入数组的元组形状:解构出的每个结果各持其型,不会塌缩成联合数组,两元素与三元素元组同样成立。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

weather: 21.5
news: deploy done | cache warm
env 2 true

实现说明

全部逻辑都在函数 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);
  },
);