≪ Today I learned.
RSS購読
    公開日
    更新日
    タグ
    JavaScript
    著者
    ダーシノ

    ES2025 Promise.try()を使う

    2024年6月にPromise.tryがStage3になった。

    関数には同期的な処理と非同期的な処理がある。関数利用者はいまから使う関数がPromiseを返すかどうか知りたくない。

    Before

    function syncFn(): string {
      return 'sync'
    }
    
    function asyncFn(): Promise<string> {
      return new Promise(r => setTimeout(() => r('async'), 100))
    }
    
    syncFn().then(a => ...)  // ERROR: Property 'then' does not exist on type 'string'.
    asyncFn().then(a => ...)

    After

    関数がPromiseを返すかどうかに関係なく Promise.then が使える

    Promise.try(syncFn).then(a => ...)
    Promise.try(asyncFn).then(a => ...)

    同期関数でもawaitが使えるが「‘await’ has no effect on the type of this expression.」と言われる。

    const syncStr = await syncFn()
    // INFO: 'await' has no effect on the type of this expression.
    
    const asyncStr = await asyncFn()

    例外が発生したときに、Promise.resolve()ではcatchできないが、Promise.try()ではcatchできる。

    const mustThrow = () => throw new Error('oh');
    Promise.resolve(mustThrow()).catch(/* 呼ばれない */);
    Promise.try(mustThrow).catch(/* 呼ばれる */)

    追記: 2024-08-23

    Promise.try()Chrome 128に実装された。


    追記: 2024-10-17

    2024年10月にStage4に移行し、ECMAScript2025に取り込まれた。