← 자료실로 돌아가기

리소스 상세 · 实用工具

保留结果顺序的异步任务池

限制同时执行的可信任务数量,单项失败会留下结果,其他任务继续处理。

본문, 예시와 라이선스는 원문을 유지합니다. 코드를 표시할 뿐 온라인으로 실행하거나 AI를 호출하지 않습니다.

리소스 상세

适合学习异步并发与失败隔离。最多200个任务、并发1至16,每项只返回短文本或简单值;不会让CPU密集任务自动并行,也不负责终止卡住的任务。

시작 전 준비

지원 환경
Windows · macOS · Linux
내용 업데이트
  • 准备Node.js 24和文本编辑器;本站仅在Node.js v24.19.0本地核对。
  • 先了解Promise、async/await;只传入可信函数。
node task-pool.mjs

先在文件所在目录打开终端。无需 npm install;本例不联网、不读写用户文件,不能直接代替生产平台接入。

흔한 문제

  • 按指定.mjs文件名保存,避免变成.mjs.txt;不需要npm install。
  • 任务不结束时池也不会结束;并发不等于增加CPU线程。
공식 설치 안내 ↗

전체 본문

// SPDX-License-Identifier: MIT
// 原创教学示例:仅运行调用方提供的可信函数,不下载或执行第三方代码。
export async function runTaskPool(tasks, concurrency = 2) {
  if (!Array.isArray(tasks) || tasks.length > 200) throw new RangeError("任务数组最多200项");
  const queue = Array.from(tasks); // 固定本批任务,外部之后追加不会让队列无界增长。
  if (queue.some(task => typeof task !== "function")) throw new TypeError("每个任务必须是函数");
  if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > 16) throw new RangeError("并发需为1至16");
  const results = new Array(queue.length);
  let nextIndex = 0;
  function checkedValue(value) {
    if (value === null || typeof value === "boolean") return value;
    if (typeof value === "number" && Number.isFinite(value)) return value;
    if (typeof value === "string" && value.length <= 2000) return value;
    throw new TypeError("教学池仅接受null、布尔值、有限数字或最多2000字符的结果");
  }
  async function worker() {
    while (nextIndex < queue.length) {
      const index = nextIndex++;
      try {
        const value = checkedValue(await queue[index]());
        results[index] = { status: "fulfilled", value };
      } catch (error) {
        let reason = "任务失败,错误说明不可读取";
        try {
          const message = error instanceof Error ? error.message : null;
          if (typeof message === "string") reason = message.slice(0, 160);
        } catch { /* 错误对象的getter也可能抛出,仍须保留后续任务。 */ }
        results[index] = { status: "rejected", reason };
      }
    }
  }
  await Promise.all(Array.from({ length: Math.min(concurrency, queue.length) }, () => worker()));
  return results; // 顺序对应原任务数组,不取决于谁先完成。
}

const tasks = [
  async () => "整理完成",
  () => { throw new Error("示例失败"); },
  async () => "归档完成",
];
console.log(JSON.stringify(await runTaskPool(tasks, 2)));

사용 방법

运行三个本地虚构任务,其中一个主动失败;观察顺序和失败不会中断后续任务。

  1. 保存完整教学代码

    点击下载代码,或复制正文保存为task-pool.mjs。保留许可说明;不要混入Markdown三反引号,确认后缀不是.mjs.txt。

  2. 在文件夹中运行

    准备Node.js 24,在保存文件的目录打开终端,执行下方node命令;不需要账号、密钥或第三方依赖。

  3. 核对结果后再修改

    应得到fulfilled、rejected、fulfilled三个结果,顺序与输入数组一致。第二项reason为示例失败;这不是联网任务。

저장 파일명
task-pool.mjs
실행 환경
Node.js 24;本站运行核验为v24.19.0。保存为.mjs,无需npm install。
의존성과 비용
代码不联网、不调用模型、不读写用户文件;无接口费用。设备和电力成本由使用者承担,接入实际应用后的成本另行核对。

실행 명령

node task-pool.mjs

예상 출력

[{"status":"fulfilled","value":"整理完成"},{"status":"rejected","reason":"示例失败"},{"status":"fulfilled","value":"归档完成"}]

로컬 검증

2026-10-22 · Node.js v24.19.0

已在本站本机运行此页原样附带的教学代码,并核对演示输出及本批注明的边界测试;不代表生产验证、全平台实测或安全审计。

적합한 용도

  • 学习异步并发限制
  • 将批次结果与原输入一一对应

사용 전 주의

  • 只运行调用方可信的函数;绝不要把用户上传的脚本直接交给任务池。
  • 队列最多200项、并发最多16;结果仅支持null、布尔值、有限数字或最多2000字符的文本。
  • 任务必须自行结束;此例没有超时或强制终止机制。长时间CPU计算仍会阻塞单线程,并发数不是CPU线程数。

작성자와 출처

저작자 표시
包子海梦 · AI辅助开发
작성자와 출처
提示集贡献者

고지 및 수정 내용

新编写的通用教学示例,发布前仍需核对来源与运行效果。

전체 라이선스

MIT

MIT License

Copyright (c) 2026 提示集贡献者

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

검증 범위

教学代码已运行

已运行完整带许可的教学文件并核对输出;不代表生产部署、平台接入或全部边界情况都已验证。

2026-10-23 Node.js v24.19.0