Created
March 24, 2018 10:01
-
-
Save evgeniyp/93c7798232501ffff477c44e41e55670 to your computer and use it in GitHub Desktop.
Limiting promises
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as promiseLimit from "promise-limit"; | |
function getRandomInt(min, max) { | |
return Math.floor(Math.random() * (max - min + 1)) + min; | |
} | |
function log(value: any) { | |
// tslint:disable-next-line:no-console | |
console.log(`>> ${value}`); | |
} | |
function longUnreliableTask(value: number) { | |
return new Promise<number>((resolve, reject) => { | |
const timeoutSecs = getRandomInt(1, 3) * 1000; | |
log(`starting job ${value} for ${timeoutSecs} ms`); | |
setTimeout(() => { | |
log(`job ${timeoutSecs} done`); | |
if (getRandomInt(1, 5) === 1) { | |
reject("FAIL"); | |
} else { | |
resolve(value * value); | |
} | |
}, timeoutSecs); | |
}); | |
} | |
async function longReliableTask(value: number) { | |
try { | |
return await longUnreliableTask(value); | |
} catch (error) { | |
log(error); | |
return null; | |
} | |
} | |
(async () => { | |
log("start"); | |
const input = [1, 2, 3, 4, 5, 6, 7, 8, 9]; | |
// const promises = input.map(longReliableTask); // usual promises | |
const limitFunc = promiseLimit(2); | |
const limitedPromises = input.map((name) => limitFunc(() => longReliableTask(name))); | |
const results = await Promise.all(limitedPromises); | |
log(`results: ${JSON.stringify(results)}`); | |
log("end"); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment