chashao
V2EX  ›  问与答

一道 promise 的题目,求大佬解答

  •  
  •   chashao · Jul 17, 2019 · 2579 views
    This topic created in 2678 days ago, the information mentioned may be changed or developed.
    class Scheduler {
        add(promiseCreator) {
              // 需要实现
        }
    }
    
    const timeout = (time) => new Promise(resolve => {
        console.log('in timeout:', time);
        setTimeout(resolve, time)
    });
    
    const scheduler = new Scheduler();
    
    const addTask = (time, order) => {
        scheduler.add(() => timeout(time))
                 .then(() => console.log(order))
    };
    
    addTask(1000, '1')
    addTask(500, '2')
    addTask(300, '3')
    addTask(400, '4')
    // output: 2 3 1 4
    // 一开始,1、2 两个任务进入队列
    // 500ms 时,2 完成,输出 2,任务 3 进队
    // 800ms 时,3 完成,输出 3,任务 4 进队
    // 1000ms 时,1 完成,输出 1
    // 1200ms 时,4 完成,输出 4
    
       
    
    
    
    
    
    
    
    11 replies  •  2019-07-19 23:19:22 +08:00
    chashao
    chashao
    OP
    Jul 17, 2019
    1
    这道题的要求是并行执行,并行最多两个任务。
    meszyouh
    meszyouh
    Jul 18, 2019 via Android
    2
    看起来还于 timeout 有关?总是接在时间最少的部分?
    kamilic
    kamilic
    Jul 18, 2019❤️1
    3
    ```javascript
    class Scheduler {
    constructor() {
    this.__maxQueueSize = 2;
    this.__runningJobs = [];
    this.__pendingQueue = [];
    }

    get isJobsFull() {
    return this.__maxQueueSize <= this.__runningJobs.length;
    }

    static jobWrapper(promiseCreator) {
    Scheduler.__jobId += 1;
    const id = Scheduler.__jobId;
    const wrappedPromise = promiseCreator().then((result) => {
    return {
    id,
    result
    };
    });
    wrappedPromise.__jobId = id;
    return wrappedPromise;
    }

    removeFinishedJob(id) {
    console.log(`remove ${id}`);
    this.__runningJobs = this.__runningJobs.reduce((curr, job) => {
    if (job.__jobId !== id) {
    curr.push(job);
    }
    return curr;
    }, []);
    console.log(this.__runningJobs);
    }

    async add(promiseCreator) {
    if (!this.isJobsFull) {
    const job = Scheduler.jobWrapper(promiseCreator);
    this.__runningJobs.push(job);
    const {result, id} = await job;
    this.removeFinishedJob(id);
    return result;
    } else {
    this.__pendingQueue.unshift(promiseCreator);
    await Promise.race(this.__runningJobs);
    if (this.__pendingQueue.length > 0) {
    return this.add(this.__pendingQueue.pop());
    }
    }
    }
    }

    Scheduler.__jobId = 0;
    ```

    昨晚一时兴起写了一下,希望对你有帮助。。
    kamilic
    kamilic
    Jul 18, 2019
    4
    ??不支持 md 的?
    zbinlin
    zbinlin
    Jul 18, 2019
    5
    这是面试题吗?如果是的话,我肯定会挂的 :(

    paste.ubuntu.com/p/Rm6dDmWxkN/
    chashao
    chashao
    OP
    Jul 18, 2019
    7
    @meszyouh 是的,timeout 最小的任务最先完成,之后的任务就能添加进来。
    chashao
    chashao
    OP
    Jul 18, 2019
    8
    @zbinlin 是字节跳动的校招题
    WhoAmIAndwhoAreU
    WhoAmIAndwhoAreU
    Jul 18, 2019
    9
    插眼
    autoxbc
    autoxbc
    Jul 19, 2019
    11
    收到 #6 @zbinlin 答案的启发,写了个简化版,应该更好理解一点

    https://gist.github.com/autoxbc/410c381aca4772736dfe22f6b4590c46
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4278 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 61ms · UTC 09:11 · PVG 17:11 · LAX 01:11 · JFK 04:11
    ♥ Do have faith in what you're doing.