Skip to content

Instantly share code, notes, and snippets.

@electrichead
Created April 13, 2022 19:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save electrichead/171d046f9c1cf1e3bd5224615493a320 to your computer and use it in GitHub Desktop.
Save electrichead/171d046f9c1cf1e3bd5224615493a320 to your computer and use it in GitHub Desktop.
forkJoin vs. race with timer
import { timer, race, forkJoin, of, throwError } from 'rxjs';
import { concatMap, map, catchError } from 'rxjs/operators';
let resolvePromise;
let rejectPromise;
const prom = new Promise((resolve, reject) => {
resolvePromise = resolve;
rejectPromise = reject;
});
function doForkJoin() {
console.time('forkJoin');
forkJoin([prom, timer(100)])
.pipe(
map((val) => `"${val}"`),
catchError(() => of('resurrection'))
)
.subscribe(
(val) => console.log('Subscribed val:', val),
(err) => {
console.log('Error happened:', err);
console.error('hmm');
console.timeEnd('forkJoin');
},
() => {
console.log('complete');
console.timeEnd('forkJoin');
}
);
setTimeout(() => {
rejectPromise('rejected promise');
resolvePromise('resolved promise');
}, 500);
}
/*
timer(1000).pipe(take(6)).subscribe(
(val) => console.log('timer val', val),
err => console.error(err),
() => console.log('timer complete')
);
*/
function doRace() {
console.time('race');
race([prom, timer(100).pipe(concatMap(() => throwError('💥')))])
.pipe(
map((val) => `"${val}"`),
catchError(() => of('resurrection'))
)
.subscribe(
(val) => console.log('Subscribed val:', val),
(err) => {
console.log('Error happened:', err);
console.error('hmm');
console.timeEnd('race');
},
() => {
console.timeEnd('race');
console.log('complete');
}
);
setTimeout(() => {
resolvePromise('resolved promise');
rejectPromise('rejected promise');
}, 500);
}
function doForkJoinWithoutPromise() {
console.time('doForkJoinWithoutPromise');
race([timer(500), timer(100)])
.pipe(
map((val) => `"${val}"`),
catchError(() => of('resurrection'))
)
.subscribe(
(val) => console.log('doForkJoinWithoutPromise val:', val),
(err) => {
console.log('Error happened:', err);
console.error('hmm');
console.timeEnd('doForkJoinWithoutPromise');
},
() => {
console.timeEnd('doForkJoinWithoutPromise');
console.log('doForkJoinWithoutPromise complete');
}
);
}
// doForkJoin();
// doForkJoinWithoutPromise();
doRace();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment