keepup-ECMAScript
  • About
  • Proposal
    • using
    • Temporal
  • ES2025
    • Promise.try
    • Sync Iterator helpers
    • Import Attributes
    • JSON Modules
    • New Set Methods
    • RegExp Modifiers
    • Duplicate named capture groups
  • ES2024
    • Resizable and growable ArrayBuffers
    • RegExp v flag with set notation + properties of strings
    • Atomics.waitAsync
    • Well-Formed Unicode Strings
    • array grouping
    • Promise withResolvers
  • ES2023
    • Symbols as WeakMap key
    • Hashbang Grammar
    • Array.findLast, findLastIndex
    • 配列の非破壊操作
  • ES2022
    • Private class fields
    • Regexp match indices
    • Top-level await
    • Private fields in-in
    • Array.at
    • Object.hasOwn
    • Class static block
    • Error cause
GitBook提供
このページ内
GitHubで編集
  1. ES2024

Promise withResolvers

前へarray grouping次へES2023

最終更新 1 年前

CtrlK

Promise, resolve, rejectを生成するユーティリティ。

// 従来このようなユーティリティがよく使われていた。
function withResolvers() {
  let resolve;
  let reject;
  const promise = new Promise((res, rej) => {
    resolve = res;
    reject = rej;
  });
  
  return { promise, resolve, reject };
}

コールバックスタイルの関数の非同期処理化ができる。

function readFileSync(path) {
  const reader = new FileReader(path);
  const { promise, resolve, reject } = withResolvers();
  reader.onerror = reject;
  reader.onload = resolve;
  reader.readAsText();
  
  return promise;
}

await textOrError = readFileSync().catch(() => "失敗");

ユーティリティを宣言せずともPromiseオブジェクトから呼び出せるようになった。

const { promise, resolve, reject } = Promise.withResolvers();

参考:使いどころが分かりやすい。 https://blog.jxck.io/entries/2024-02-10/promise.withresolvers.html