CodeSampleX

Пример

p-cancelable 2.1.1: create and cancel a promise with PCancelable and handle CancelError

Проверенный пример — npm p-cancelable 2.1.1: create and cancel a promise with PCancelable and handle CancelError. Контракт выполнен на node 22 · linux…

sha256:17ee1c909e67662d1697e1def90d6dc1b4d171896c9de9c94a6451e39d4d122d

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
2
Ключи подписи, собравшие его
1
Заявленная среда node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Среды запусков проверки

Окружение Контракт Этапы Запуск
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-08-26
node 22 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2…
2026-09-07

Кейс

HOW
Цель
create and cancel a promise with PCancelable and handle CancelError
Пакеты
Символы
  • PCancelable
  • PCancelable.CancelError
Окружение
node 22.23.2
Создан
2026-08-26T08:17:19Z

Контракт

  1. resolves normally with the expected value when not canceled
  2. canceling a pending promise synchronously sets isCanceled to true and invokes onCancel handlers
  3. canceling rejects the promise with CancelError and error.isCanceled is true
  4. custom cancellation reason is preserved in CancelError message
  5. setting onCancel.shouldReject to false prevents promise rejection upon cancellation
  6. PCancelable.fn converts a function into a cancelable promise function

Файлы

  • PROMPT.md
  • csx.json
  • index.js
  • package-lock.json
  • package.json
  • spec.json
  • test/contract.mjs

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: create and cancel a promise with PCancelable and handle CancelError
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/p-cancelable@2.1.1
Demonstrate these symbols/APIs:
  - PCancelable
  - PCancelable.CancelError

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:258b2f4af3204a62a19c1e27cf6790662ee5cc8e3b445ad6635bc13ccc999af9","contract":["resolves normally with the expected value when not canceled","canceling a pending promise synchronously sets isCanceled to true and invokes onCancel handlers","canceling rejects the promise with CancelError and error.isCanceled is true","custom cancellation reason is preserved in CancelError message","setting onCancel.shouldReject to false prevents promise rejection upon cancellation","PCancelable.fn converts a function into a cancelable promise function"],"goal":"create and cancel a promise with PCancelable and handle CancelError","kind":"HOW","packages":["pkg:npm/p-cancelable@2.1.1"],"schemaVersion":1,"symbols":["PCancelable","PCancelable.CancelError"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"esm","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/p-cancelable@2.1.1"],"schemaVersion":1,"subject":"pkg:npm/p-cancelable@2.1.1","symbols":["PCancelable","PCancelable.CancelError"],"verifierAdapter":"node-typescript@1"}
index.js
import PCancelable, { CancelError } from 'p-cancelable';

/**
 * Creates a delay promise that can be canceled.
 * @param {number} ms - Milliseconds to delay.
 * @param {string} [value] - Value to resolve with.
 * @returns {PCancelable<string>} Cancelable promise.
 */
export function createCancellableDelay(ms, value = 'done') {
  return new PCancelable((resolve, reject, onCancel) => {
    const timer = setTimeout(() => {
      resolve(value);
    }, ms);

    onCancel(() => {
      clearTimeout(timer);
    });
  });
}

/**
 * Creates a cancelable operation where cancellation does not reject.
 * @param {Function} cleanupFn - Cleanup callback.
 * @returns {PCancelable<string>} Cancelable promise.
 */
export function createSilentCancellable(cleanupFn) {
  return new PCancelable((resolve, reject, onCancel) => {
    onCancel.shouldReject = false;
    onCancel(() => {
      if (cleanupFn) {
        cleanupFn();
      }
    });

    const timer = setTimeout(() => {
      resolve('completed');
    }, 100);

    onCancel(() => {
      clearTimeout(timer);
    });
  });
}

export { PCancelable, CancelError };
package-lock.json
{
  "name": "sample-p-cancelable",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-p-cancelable",
      "version": "1.0.0",
      "dependencies": {
        "p-cancelable": "2.1.1"
      }
    },
    "node_modules/p-cancelable": {
      "version": "2.1.1",
      "resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-2.1.1.tgz",
      "integrity": "sha512-BZOr3nRQHOntUjTrH8+Lh54smKHoHyur8We1V8DSMVrl5A2malOOwuJRnKRDjSnkoeBh4at6BwEnb5I7Jl31wg==",
      "license": "MIT",
      "engines": {
        "node": ">=8"
      }
    }
  }
}
package.json
{
  "name": "sample-p-cancelable",
  "version": "1.0.0",
  "private": true,
  "description": "create and cancel a promise with PCancelable and handle CancelError",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "p-cancelable": "2.1.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "create and cancel a promise with PCancelable and handle CancelError",
  "kind": "HOW",
  "packages": [
    "pkg:npm/p-cancelable@2.1.1"
  ],
  "symbols": [
    "PCancelable",
    "PCancelable.CancelError"
  ]
}
test/contract.mjs
import assert from 'node:assert';
import PCancelable, { CancelError } from 'p-cancelable';
import { createCancellableDelay, createSilentCancellable } from '../index.js';

// 1. resolves normally with the expected value when not canceled
{
  const result = await createCancellableDelay(10, 'success');
  assert.strictEqual(result, 'success');
}

// 2. canceling a pending promise synchronously sets isCanceled to true and invokes onCancel handlers
{
  let cleanupCalled = false;
  const p = new PCancelable((resolve, reject, onCancel) => {
    const timer = setTimeout(() => resolve('ok'), 1000);
    onCancel(() => {
      cleanupCalled = true;
      clearTimeout(timer);
    });
  });

  assert.strictEqual(p.isCanceled, false);
  p.cancel();
  assert.strictEqual(p.isCanceled, true);
  assert.strictEqual(cleanupCalled, true);

  // Catch rejection so it does not trigger unhandledRejection
  await assert.rejects(
    async () => {
      await p;
    },
    (err) => {
      assert.ok(err instanceof CancelError);
      assert.strictEqual(err.isCanceled, true);
      return true;
    }
  );
}

// 3. canceling rejects the promise with CancelError and error.isCanceled is true
{
  const p = createCancellableDelay(1000);
  p.cancel();

  await assert.rejects(
    async () => {
      await p;
    },
    (err) => {
      assert.ok(err instanceof CancelError);
      assert.ok(err instanceof PCancelable.CancelError);
      assert.strictEqual(err.name, 'CancelError');
      assert.strictEqual(err.isCanceled, true);
      assert.strictEqual(err.message, 'Promise was canceled');
      return true;
    }
  );
}

// 4. custom cancellation reason is preserved in CancelError message
{
  const p = createCancellableDelay(1000);
  p.cancel('Operation timed out by caller');
  assert.strictEqual(p.isCanceled, true);

  await assert.rejects(
    async () => {
      await p;
    },
    (err) => {
      assert.ok(err instanceof CancelError);
      assert.strictEqual(err.name, 'CancelError');
      assert.strictEqual(err.isCanceled, true);
      assert.strictEqual(err.message, 'Operation timed out by caller');
      return true;
    }
  );
}

// 5. setting onCancel.shouldReject to false prevents promise rejection upon cancellation
{
  let cleanedUp = false;
  const p = createSilentCancellable(() => {
    cleanedUp = true;
  });

  assert.strictEqual(p.isCanceled, false);
  p.cancel();
  assert.strictEqual(p.isCanceled, true);
  assert.strictEqual(cleanedUp, true);

  let rejected = false;
  p.catch(() => {
    rejected = true;
  });
  await new Promise((r) => setTimeout(r, 50));
  assert.strictEqual(rejected, false);
}

// 6. PCancelable.fn converts a function into a cancelable promise function
{
  let cancelled = false;
  const fn = PCancelable.fn((arg1, onCancel) => {
    return new Promise((resolve) => {
      const timer = setTimeout(() => resolve(`hello ${arg1}`), 1000);
      onCancel(() => {
        cancelled = true;
        clearTimeout(timer);
      });
    });
  });

  const p = fn('world');
  assert.strictEqual(p.isCanceled, false);
  p.cancel('custom error');
  assert.strictEqual(p.isCanceled, true);
  assert.strictEqual(cancelled, true);

  await assert.rejects(
    async () => {
      await p;
    },
    (err) => {
      assert.ok(err instanceof CancelError);
      assert.strictEqual(err.name, 'CancelError');
      assert.strictEqual(err.isCanceled, true);
      assert.strictEqual(err.message, 'custom error');
      return true;
    }
  );
}

Исходный сидер

аноним