Throttle amount of promises open at a given time

前端 未结 5 1411
醉话见心
醉话见心 2020-12-03 15:28

The following Typescript performs each call to doSomething(action) one at a time. (Meaning the second item in the list does not get a call made until the first

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-03 16:24

    You can do this with a pub-sub pattern. I too am not familiar with typescipt, and I don't know if this is happening in the browser or at the backend. I'll just write the pseudoCode for this (assuming it's backend):

    //I'm assuming required packages are included e.g. events = require("events");
    let limit = 10;
    let emitter = new events.EventEmitter();
    
    for(let i=0; i {
            console.log(`Action Done: ${actionResult}`);
            emitter.emit('grabTheNextOne', listOfActions.pop());
        });
    }
    
    emitter.on('grabTheNextOne', fetchNext);
    

    EventEmitter is part of NodeJS, if you are working in Node. If in the browser, you can use the normal events model. The key idea here is the Publish-Subscribe pattern.

提交回复
热议问题