CodeSampleX

Exemple

bluebird 3.7.2: Promise.map with concurrency limit to transform async items

Échantillon vérifié pour npm bluebird 3.7.2: Promise.map with concurrency limit to transform async items. Le contrat s'est exécuté sur node 22 · linux…

sha256:80c9caca5fc5ac442184f5a574ccd00d1e9fdc8c6ea49c69188a528350e2fdf0

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
1
Clés de signature qui l’ont compilé
1
Environnement déclaré node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
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

Cas

HOW
Objectif
Promise.map with concurrency limit to transform async items
Paquets
Symboles
  • Promise.map
Environnement
node 22.23.2
Créé
2026-08-26T09:26:36Z

Contrat

  1. Promise.map iterates over input items, applies async mapper, and resolves to array of transformed results in original order
  2. Promise.map enforces concurrency option so no more than specified number of mapper promises execute simultaneously
  3. Promise.map accepts input arrays containing Promises or mixed values and resolves items before passing to mapper
  4. Promise.map rejects immediately when any mapper operation throws or returns a rejected promise
  5. Promise.map handles empty iterable resolving immediately to empty array without invoking mapper
  6. Promise.map passes current item index and total array length to mapper callback

Fichiers

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

Télécharger l’artefact source (tar.gz)

Code source

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: Promise.map with concurrency limit to transform async items
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/bluebird@3.7.2
Demonstrate these symbols/APIs:
  - Promise.map

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:057a63ec42fb0c266f6e13faba198e260206cda29d60fe0a67dd50ceb4e42e92","contract":["Promise.map iterates over input items, applies async mapper, and resolves to array of transformed results in original order","Promise.map enforces concurrency option so no more than specified number of mapper promises execute simultaneously","Promise.map accepts input arrays containing Promises or mixed values and resolves items before passing to mapper","Promise.map rejects immediately when any mapper operation throws or returns a rejected promise","Promise.map handles empty iterable resolving immediately to empty array without invoking mapper","Promise.map passes current item index and total array length to mapper callback"],"goal":"Promise.map with concurrency limit to transform async items","kind":"HOW","packages":["pkg:npm/bluebird@3.7.2"],"schemaVersion":1,"symbols":["Promise.map"]},"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/bluebird@3.7.2"],"schemaVersion":1,"subject":"pkg:npm/bluebird@3.7.2","symbols":["Promise.map"],"verifierAdapter":"node-typescript@1"}
index.mjs
import Promise from 'bluebird';

/**
 * Transforms an array of items asynchronously with a concurrency limit.
 * @param {Array<any>|Promise<Array<any>>} items - Array of items or promises
 * @param {Function} mapper - Async mapper function (item, index, length) => Promise<result> | result
 * @param {number} [concurrency] - Maximum number of concurrent mapper executions
 * @returns {Promise<Array<any>>} Bluebird Promise resolving to transformed array
 */
export function mapConcurrent(items, mapper, concurrency) {
  const options = concurrency !== undefined ? { concurrency } : undefined;
  return Promise.map(items, mapper, options);
}

/**
 * Executes async tasks with limited concurrency and tracks peak active count.
 * @param {Array<Function>} taskFns - Array of task-producing functions
 * @param {number} concurrency - Concurrency limit
 * @returns {Promise<{ results: Array<any>, peakConcurrency: number }>}
 */
export function executeWithConcurrencyTracker(taskFns, concurrency) {
  let activeCount = 0;
  let peakConcurrency = 0;

  return Promise.map(
    taskFns,
    async (taskFn, index) => {
      activeCount++;
      if (activeCount > peakConcurrency) {
        peakConcurrency = activeCount;
      }
      try {
        const result = await taskFn(index);
        return result;
      } finally {
        activeCount--;
      }
    },
    { concurrency }
  ).then((results) => ({
    results,
    peakConcurrency
  }));
}
package-lock.json
{
  "name": "sample-bluebird-promise-map",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-bluebird-promise-map",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "bluebird": "3.7.2"
      }
    },
    "node_modules/bluebird": {
      "version": "3.7.2",
      "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz",
      "integrity": "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==",
      "license": "MIT"
    }
  }
}
package.json
{
  "name": "sample-bluebird-promise-map",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "license": "MIT-0",
  "dependencies": {
    "bluebird": "3.7.2"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "Promise.map with concurrency limit to transform async items",
  "kind": "HOW",
  "packages": [
    "pkg:npm/bluebird@3.7.2"
  ],
  "symbols": [
    "Promise.map"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import Promise from 'bluebird';
import { mapConcurrent, executeWithConcurrencyTracker } from '../index.mjs';

// 1. Promise.map iterates over input items, applies async mapper, and resolves to array of transformed results in original order
{
  const inputs = [10, 20, 30, 40];
  const delays = [40, 10, 30, 20];

  const results = await Promise.map(inputs, async (val, idx) => {
    await Promise.delay(delays[idx]);
    return val * 2;
  });

  assert.deepEqual(results, [20, 40, 60, 80]);

  const helperResults = await mapConcurrent(inputs, async (val, idx) => {
    await Promise.delay(delays[idx]);
    return `item-${val}`;
  });
  assert.deepEqual(helperResults, ['item-10', 'item-20', 'item-30', 'item-40']);
}

// 2. Promise.map enforces concurrency option so no more than specified number of mapper promises execute simultaneously
{
  const taskCount = 10;
  const concurrencyLimit = 3;
  let currentlyRunning = 0;
  let maxObservedRunning = 0;

  const tasks = Array.from({ length: taskCount }, (_, i) => async () => {
    currentlyRunning++;
    if (currentlyRunning > maxObservedRunning) {
      maxObservedRunning = currentlyRunning;
    }
    await Promise.delay(25);
    currentlyRunning--;
    return i * 10;
  });

  const { results, peakConcurrency } = await executeWithConcurrencyTracker(
    tasks,
    concurrencyLimit
  );

  assert.equal(results.length, taskCount);
  assert.deepEqual(
    results,
    [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
  );
  assert.ok(maxObservedRunning <= concurrencyLimit, `maxObservedRunning (${maxObservedRunning}) must be <= ${concurrencyLimit}`);
  assert.equal(peakConcurrency, concurrencyLimit);
  assert.equal(currentlyRunning, 0);
}

// 3. Promise.map accepts input arrays containing Promises or mixed values and resolves items before passing to mapper
{
  const mixedInput = [
    Promise.resolve('alpha'),
    'bravo',
    Promise.delay(10).then(() => 'charlie'),
    Promise.resolve('delta')
  ];

  const processed = await Promise.map(mixedInput, async (item) => {
    assert.equal(typeof item, 'string');
    return item.toUpperCase();
  }, { concurrency: 2 });

  assert.deepEqual(processed, ['ALPHA', 'BRAVO', 'CHARLIE', 'DELTA']);
}

// 4. Promise.map rejects immediately when any mapper operation throws or returns a rejected promise
{
  const items = [1, 2, 3, 4, 5];

  await assert.rejects(
    async () => {
      await Promise.map(
        items,
        async (item) => {
          if (item === 3) {
            throw new Error('Mapper failed on item 3');
          }
          await Promise.delay(15);
          return item;
        },
        { concurrency: 2 }
      );
    },
    {
      name: 'Error',
      message: 'Mapper failed on item 3'
    }
  );
}

// 5. Promise.map handles empty iterable resolving immediately to empty array without invoking mapper
{
  let called = false;
  const result = await Promise.map([], async () => {
    called = true;
    return 1;
  });

  assert.deepEqual(result, []);
  assert.equal(called, false);
}

// 6. Promise.map passes current item index and total array length to mapper callback
{
  const letters = ['a', 'b', 'c'];
  const recordedIndices = [];
  const recordedLengths = [];

  const mapped = await Promise.map(letters, (item, index, length) => {
    recordedIndices.push(index);
    recordedLengths.push(length);
    return `${item}-${index}-${length}`;
  });

  assert.deepEqual(mapped, ['a-0-3', 'b-1-3', 'c-2-3']);
  assert.deepEqual(recordedIndices, [0, 1, 2]);
  assert.deepEqual(recordedLengths, [3, 3, 3]);
}

console.log('All Promise.map contract tests passed.');

Seeder d'origine

anonyme