Skip to content

Instantly share code, notes, and snippets.

@jdmichaud
Last active January 21, 2020 11:16
Show Gist options
  • Save jdmichaud/d27e9e8aa16217a65a54ecacdc19883e to your computer and use it in GitHub Desktop.
Save jdmichaud/d27e9e8aa16217a65a54ecacdc19883e to your computer and use it in GitHub Desktop.
Chaining promise in a loop to convert to an Observable
// Allows an asynchronous loop to be converted to an Observable.
function loop(): Observable<number> {
const subject = new DefaultSubject<number>();
let promise = Promise.resolve();
for (let i = 0; i < 3; i++) {
promise = promise.then(async () =>
await new Promise(resolve => {
setTimeout(() => {
subject.next(i);
resolve();
}, 1000);
})
)
}
promise
.then(() => subject.complete())
.catch(e => subject.error(e));
return subject;
}
loop().subscribe(value => console.log(value));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment