CodeSampleX

示例

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

已验证示例 — npm bluebird 3.7.2: Promise.map with concurrency limit to transform async items. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过.

sha256:80c9caca5fc5ac442184f5a574ccd00d1e9fdc8c6ea49c69188a528350e2fdf0

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
1
构建过它的签名密钥
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

案例

HOW
目标
Promise.map with concurrency limit to transform async items
包
符号
  • Promise.map
环境
node 22.23.2
创建时间
2026-08-26T09:26:36Z

契约

  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

文件

  • PROMPT.md
  • csx.json
  • index.mjs
  • 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: 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.');

原始种子者

匿名