0

Why the second promise doesn't work?

public upload(): Promise<any> {
    return (this.loader.file as Promise<File>)
        .then(file => {
            const uploadImageUrl$: Subject<string> = new Subject<string>();;
            this.uploadImageService.uploadFile(file).subscribe( data => {
                uploadImageUrl$.next(this.uploadImageService.getImageUrlByResponse(data));
            });
            uploadImageUrl$.subscribe(console.log); //return url
            return uploadImageUrl$.toPromise();
        })
        .then(url => {
            console.log(url); //doesn't work
            return {default: url};
        });
}

I was expecting for the returned url

Serkan Sipahi
  • 691
  • 6
  • 19
prolina
  • 185
  • 4
  • 14

1 Answers1

3

The problem is, as long as your subject is not completed, the Promise can't be resolved and therefore cannot be passed to the next then.

See example:

import { of, subject } from 'rxjs'; 
import { map } from 'rxjs/operators';

const subject$ = new Subject<string>();

subject$.toPromise().then(value => console.log(value));

subject$.next('hello!');
subject$.complete();

If you comment out the complete in the Stackblitz example, you will see that it works.

https://stackblitz.com/edit/rxjs-n4jib6?file=index.ts

Please let me know if its works, thanks!

Serkan Sipahi
  • 691
  • 6
  • 19
  • 1
    Thank you) After that `uploadImageUrl$.next(this.uploadImageService.getImageUrlByResponse(data));` I added `uploadImageUrl$.complete()` and it solves my problem. – prolina May 30 '20 at 11:38