Skip to content

Instantly share code, notes, and snippets.

@KATT
Created March 18, 2019 21:55
Show Gist options
  • Save KATT/b318281656ea089586bdab4f35690e35 to your computer and use it in GitHub Desktop.
Save KATT/b318281656ea089586bdab4f35690e35 to your computer and use it in GitHub Desktop.
function deferred<T>() {
let resolve: (value: PromiseLike<T> | T) => void;
let reject: (reason: Error) => void;
let promise = new Promise<T>((_resolve, _reject) => {
resolve = _resolve;
reject = _reject;
});
return { promise, resolve, reject };
}
function randomIntFromInterval(min: number, max: number) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
async function myAsyncFunction(val: string) {
const { resolve, promise } = deferred<string>();
setTimeout(
() => resolve(`${val} - computed`),
randomIntFromInterval(200, 3000)
);
return promise;
}
async function main() {
for (let i = 0; i < 10; i++) {
const input = i + 1 + '';
myAsyncFunction(input)
.then(v => console.log(v))
.catch(e => console.error(`${i} failed`));
}
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment