Last active
January 21, 2020 11:16
-
-
Save jdmichaud/d27e9e8aa16217a65a54ecacdc19883e to your computer and use it in GitHub Desktop.
Chaining promise in a loop to convert to an Observable
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
// 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