Promise.try Wraps Sync Throws

Start async chains with Promise.try so sync throws become rejections: extra arguments pass straight to the function without an arrow wrapper.

JavascriptResilience

Code

javascriptsnippet
25 lines
// Promise.try:把可能同步抛错的启动函数收进 promise 链
function parseCount(raw) {
  const n = Number(raw);
  if (!Number.isInteger(n) || n < 0) {
    throw new TypeError('count must be a non-negative integer');
  }
  return n;
}

// 手写等价:先 Promise.resolve() 再 .then(),才能接住同步抛错
function parseCountViaThen(raw) {
  return Promise.resolve().then(() => parseCount(raw));
}

console.log('ok    :', await Promise.try(() => parseCount('7')));
console.log('manual:', await parseCountViaThen('7'));
// 额外参数直接跟在函数后面,不用再包一层箭头函数
console.log('args  :', await Promise.try(parseCount, '12'));

try {
  await Promise.try(() => parseCount('-1'));
} catch (err) {
  // 同步抛错进入 rejection:链路从第一步就在错误通道上
  console.log('bad   :', err.message);
}

Output

Captured from a sandboxed run of this snippet in the build pipeline.

ok    : 7
manual: 7
args  : 12
bad   : count must be a non-negative integer

How it works

The working surface is the functions parseCount and parseCountViaThen — everything else is wiring.

The asynchronous flow is linearized with await, keeping failure handling local. When the guard condition holds, TypeError is thrown rather than a bogus value returned.

Putting it to use

The primary signature is function parseCount(raw)

Running the file prints labeled results such as manual: — each operation’s effect is visible in the output.

Core lines

return Promise.resolve().then(() => parseCount(raw));
await Promise.try(() => parseCount('-1'));
throw new TypeError('count must be a non-negative integer');

Interactive Tools for This Topic

FAQ

What happens on invalid input?
It throws `TypeError` before any real work runs — handle it at the call site or let it propagate deliberately.
Is a package install part of the setup?
No. Installation is unnecessary because only built-in APIs are used. The file defines `parseCount`, `parseCountViaThen` at load time.