为什么从主题 (Observable) 转换的承诺不能按预期工作 [英] Why converted promise from Subject (Observable) does not work as expected

查看:34
本文介绍了为什么从主题 (Observable) 转换的承诺不能按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么第二个承诺不起作用?

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};
        });
}

我期待返回的网址

推荐答案

问题是,只要你的subject没有完成,Promise就无法解决,因此无法传递到下一个then.

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.

参见示例:

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();

如果您将 Stackblitz 示例中的完整注释掉,您将看到它有效.

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!

这篇关于为什么从主题 (Observable) 转换的承诺不能按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆