向各位前端工程师请教一道笔试题,有关JS并发处理异步任务的

const assert = require('assert');

/**
 * --- 问题描述 ---
 *
 * 给出一组异步任务方法,和允许同时执行的个数,实现一个方法,用于并发执行异步任务
 *
 * --- 说明 ---
 *
 * - 当有任务执行完毕后,自动补充任务,始终保持正在执行的任务有 `concurrency` 个
 * - 返回 { resolved: [], rejected: [] }
 *
 **/

async function parallel(tasks, concurrency) {

}

/*******测试部分*******/
module.exports = async function doTest() {
  try {
    const child_process = require('child_process');
    const fs = require('fs');
    const path = require('path');
    const util = require('util');
    const readFile = util.promisify(fs.readFile);
    const exec = util.promisify(child_process.exec);

    const tasks = [
      () => readFile(__filename, 'utf-8'),
      () => Promise.resolve('foo'),
      () => exec('npm -v'),
      () => readFile(path.join(__dirname, '../package.json'), 'utf-8'),
      () => process.cpuUsage(),
      () => exec('node -v'),
      () => Promise.reject(new Error('bar')),
      () => exec('ls -al'),
      () => new Promise(resolve => process.nextTick(resolve)),
      () => exec('whoami')
    ];
    const { resolved, rejected } = await parallel(tasks, 3);
    assert.equal(resolved.length, 9);
    assert.equal(rejected.length, 1);
    return '通过';
  } catch (err) {
    return '不通过';
  }
};

#笔经#
全部评论
尝试一下,如有错误请大佬指正! async function parallel(tasks, n) {   const ans = {resolved: [], rejected: []};   const executing = new Set();   for (const task of tasks) {     const e = task().then(res => {       executing.delete(e);       ans.resolved.push(res);     }).catch(err => {       executing.delete(e);       ans.rejected.push(err);     });     executing.add(e);     if (executing.size >= n) {       await Promise.race(executing);     }   }   while (executing.size > 0) {     await Promise.race(executing);   }   return ans; }
点赞 回复 分享
发布于 2022-10-19 00:34 浙江
这个问题解决了吗?前几天面试也碰到类似的了
点赞 回复 分享
发布于 2021-08-01 21:42

相关推荐

今年hc多吗。。双非真无力了
投递比亚迪等公司10个岗位
点赞 评论 收藏
分享
09-13 17:43
已编辑
北京化工大学 硬件开发
易才一飞:感觉项目写细节一些吧,掌握技能和校内经历感觉占比太大,而且这是找嵌软还是硬件呢,似乎大家都说要有针对的写相关技术才好吧
点赞 评论 收藏
分享
09-13 10:40
门头沟学院 Java
听别人介绍,刷了一堆力扣题,考场上写函数,一直无法通过。赛后才知道要自己写输入输出,力扣害人不浅
Silencer76:输入输出练习题单,请https://www.nowcoder.com/exam/oj?page=1&tab=%E7%AE%97%E6%B3%95%E7%AC%94%E9%9D%A2%E8%AF%95%E7%AF%87&topicId=372
点赞 评论 收藏
分享
评论
点赞
2
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务