← 中文资源

简体中文版本

惰性异步初始化共享单个 Promise

首次调用才启动初始化,所有调用方共享同一个 Promise;失败时清空引用让下一次调用重新发起,而不是永远卡在已拒绝的旧承诺上等失败。

阅读英文原文

运行结果

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

callers share one promise: true
first init failed: config missing
retry attempt: 2 db://local
settled init reused: true attempts still: 2

实现说明

惰性异步初始化共享单个 Promise以函数 connect、getClient、main为骨架。 异步流被 await 线性化,失败处理保持局部。 返回的是新建的值,不复用入参。

使用要点

  • 直接运行文件,输出会带上标签,比如 callers share one promise:、first init failed:、retry attempt:——输出的每一行都能指回产生它的那次调用。
  • 执行文件,main 会按顺序走完 getClient。

常见问题

connect 会修改传入的参数吗?

没有原地修改——函数读取输入并返回新值。

运行「惰性异步初始化共享单个 Promise」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 callers share one promise:、first init failed:、retry attempt: 这类标签。

签名一览:function connect(attempt)

核心语句

clientPromise = connect(attempts).catch((err) => {
  clientPromise = null; // drop the poisoned promise so a retry can start
  throw err;
});
return new Promise((resolve, reject) => {
  setTimeout(() => {
    if (attempt === 1) reject(new Error('config missing'));
    else resolve({ endpoint: 'db://local', ready: true });
  }, 5);
});
const client = await getClient();

代码示例

// Lazy async init: a single expensive setup starts on the first call, every
// caller awaits the same promise, and a rejection resets it for a retry
let clientPromise = null;
let attempts = 0;

function connect(attempt) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (attempt === 1) reject(new Error('config missing'));
      else resolve({ endpoint: 'db://local', ready: true });
    }, 5);
  });
}

function getClient() {
  if (!clientPromise) {
    attempts += 1;
    clientPromise = connect(attempts).catch((err) => {
      clientPromise = null; // drop the poisoned promise so a retry can start
      throw err;
    });
  }
  return clientPromise;
}

async function main() {
  const firstCall = getClient();
  console.log('callers share one promise:', firstCall === getClient());
  try {
    await firstCall;
  } catch (err) {
    console.log('first init failed:', err.message);
  }
  const client = await getClient();
  console.log('retry attempt:', attempts, client.endpoint);
  const cached = await getClient();
  console.log('settled init reused:', cached === client, 'attempts still:', attempts);
}

main();