CodeSampleX

Exemplo

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

Amostra verificada para npm p-cancelable 2.1.1: create and cancel a promise with PCancelable and handle CancelError. O contrato rodou em node 22 · linux…

sha256:17ee1c909e67662d1697e1def90d6dc1b4d171896c9de9c94a6451e39d4d122d

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
2
Chaves de assinatura que o compilaram
1
Ambiente declarado node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
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

Caso

HOW
Objetivo
create and cancel a promise with PCancelable and handle CancelError
Pacotes
Símbolos
  • PCancelable
  • PCancelable.CancelError
Ambiente
node 22.23.2
Criado
2026-08-26T08:17:19Z

Contrato

  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

Arquivos

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

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

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;
    }
  );
}

Seeder de origem

anônimo