Skip to content

TypeScript Promise API

TypeScript 内置工具类型,用于转换和组合类型。

1 class · 10 methods

工具类型

10 methods

由 TypeScript 的 lib.es5.d.ts 提供的全局工具类型。

Promise.all(iterable)

将 T 的所有属性设为可选。

Parameters

NameTypeDescription
iterableIterable<Promise | non-Promise>源类型。

Returns

Promise<Array>

Example

javascript
const [user, posts, comments] = await Promise.all([
  fetchUser(1),
  fetchPosts(1),
  fetchComments(1),
]);
// If any fails, the whole thing rejects immediately.
Promise.allSettled(iterable)

将 T 的所有属性设为必需(移除 ? 修饰符)。

Parameters

NameTypeDescription
iterableIterable<Promise | non-Promise>源类型。

Returns

Promise<Array<{ status: 'fulfilled', value } | { status: 'rejected', reason }>>

Example

javascript
const results = await Promise.allSettled([
  fetch('/api/a'),
  fetch('/api/b'),
  fetch('/api/c'),
]);
results.forEach(r => {
  if (r.status === 'fulfilled') console.log('OK:', r.value);
  else console.log('Fail:', r.reason);
});
Promise.any(iterable)

将 T 的所有属性设为只读。

Parameters

NameTypeDescription
iterableIterable<Promise | non-Promise>源类型。

Returns

Promise<value>

Example

javascript
// Use the fastest-responding mirror
const fastest = await Promise.any([
  fetch('https://mirror1.example.com/api'),
  fetch('https://mirror2.example.com/api'),
  fetch('https://mirror3.example.com/api'),
]);
// fastest is the response of the first one to succeed.
Promise.race(iterable)

构造一个键为 K、值为 V 的对象类型。

Parameters

NameTypeDescription
iterableIterable<Promise | non-Promise>键(string | number | symbol 联合类型)。

Returns

Promise<value>

Example

javascript
// 5-second timeout
function withTimeout(promise, ms) {
  return Promise.race([
    promise,
    new Promise((_, reject) =>
      setTimeout(() => reject(new Error('timeout')), ms)
    ),
  ]);
}
const result = await withTimeout(fetch('/slow-api'), 5000);
Promise.resolve(value)

从 T 中选取键 K。

Parameters

NameTypeDescription
valueany源类型。

Returns

Promise<value>

Example

javascript
// Ensure async return type
function getData(sync = false) {
  if (sync) return Promise.resolve(cachedData);
  return fetch('/api/data').then(r => r.json());
}
// Awaiting Promise.resolve(value) is a microtask:
await Promise.resolve();  // yields to the event loop
Promise.reject(reason)

构造一个包含 T 中除 K 以外所有属性的类型。

Parameters

NameTypeDescription
reasonany源类型。

Returns

Promise<never>

Example

javascript
// Validate before continuing
function requireAuth(user) {
  if (!user) return Promise.reject(new Error('Unauthorized'));
  return Promise.resolve(user);
}
try {
  await requireAuth(null);
} catch (e) {
  console.error(e.message);  // 'Unauthorized'
}
Promise.try(executor)since ES2025

从联合类型 T 中排除所有可赋值给 U 的类型。

Parameters

NameTypeDescription
executor() => value | Promise源联合类型。

Returns

Promise<value>

Example

javascript
// Old way: dual try/catch + .catch
async function load() {
  try {
    const data = JSON.parse(raw);  // sync throw
    return await fetch('/save', { body: JSON.stringify(data) });
  } catch (e) {
    handle(e);  // catches both
  }
}
// New way: Promise.try handles both
Promise.try(() => JSON.parse(raw))
  .then(data => fetch('/save', { body: JSON.stringify(data) }))
  .catch(handle);  // catches both sync and async errors
promise.then(onFulfilled, onRejected?)

从联合类型 T 中提取所有可赋值给 U 的类型。

Parameters

NameTypeDescription
onFulfilled(value) => result | Promise源联合类型。
onRejected(reason) => result | Promise要提取的类型。

Returns

Promise<result>

Example

javascript
// Chaining with value transformation
fetch('/api/user/1')
  .then(r => r.json())           // Promise resolves with parsed JSON
  .then(user => user.name)       // Resolves with the name string
  .then(name => `Hello, ${name}`)
  .then(greeting => console.log(greeting));
promise.catch(onRejected)

从 T 中排除 null 和 undefined。

Parameters

NameTypeDescription
onRejected(reason) => result | Promise源类型。

Returns

Promise<result>

Example

javascript
// Recovery: catch returns a value, so the chain continues
fetch('/api/primary')
  .catch(() => fetch('/api/fallback'))  // try fallback
  .then(r => r.json())
  .then(data => render(data));
// Without recovery (just log):
promise.catch(err => console.error('failed:', err));
promise.finally(onFinally)

返回函数类型 T 的返回类型。

Parameters

NameTypeDescription
onFinally() => void函数类型。

Returns

Promise<value>

Example

javascript
// Show/hide loading spinner regardless of outcome
button.disabled = true;
showSpinner();
fetch('/api/save', { method: 'POST', body: data })
  .then(r => showToast('Saved!'))
  .catch(e => showToast('Error: ' + e.message))
  .finally(() => {
    button.disabled = false;
    hideSpinner();
  });