Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 21:13
- // Given urls ['url1', 'url2', 'url2', 'url3'...], limit
- // Function `process` should `get` all urls, respecting limit and return when finished.
- // Limit means that at the same time there should be N (limit) requests in progress, at least and at most
- // Duplicate urls shouldn't be processed again, but the final order should be the same
- // Get is used to mock requests
- function get(url) {
- return Promise.resolve("result" + url);
- }
- // Checkpoint 21:22
- // Checkpoint 21:34
- function process(urls, limit) {
- async function _process() {
- const urlMap = {};
- const first10urls = urls.slice(0, limit);
- const restUrls = urls.slice(limit);
- const res = [];
- function processNext(url, resolve) {
- if (!urlMap[url]) {
- urlMap[url] = get(url).then(res => {
- if (restUrls.length) {
- nextUrl = restUrls.pop();
- processNext(nextUrl, resolve);
- } else {
- resolve();
- }
- return res;
- });
- }
- }
- function wait() {
- return new Promise(resolve => {
- first10urls.forEach(url => {
- processNext(url, resolve);
- });
- });
- }
- await wait();
- // urlMap should be full by that time
- for (let url of urls) {
- const data = await urlMap[url];
- res.push(data);
- }
- return res;
- }
- return _process();
- }
- // 21:39
- // Handle wait for all promies
- // Done 21:45
- console.log(
- process(["url1", "url2", "url3", "url4", "url5", "url6", "url7", "url2"], 2)
- );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement