【问题标题】:Calling promise resolve multiple times, returning same old results多次调用promise resolve,返回相同的旧结果
【发布时间】:2019-10-02 17:07:25
【问题描述】:

在我的 Angular 项目中,我有两个独立的组件。

parent.component.ts

mypromise = this.httpClient.get<any>('http://localhost').toPromise()

parent.component.html

<app-children #child [promise]="mypromise"></app-children>

<button (click)="child.update()">Update now!</button>

child.component.ts

@Input promise: Promise<any>

ngOnInit(){
  this.getMyPromise()

  //results:
  //[{id: 1, text: 'abc'}, {id: 2, text: 'abcd'}]  
}

update(){
  this.getMyPromise()
  //expected:
  //[{id: 1, text: 'abc'}, {id: 2, text: 'abcd'}, {id: 3, text: 'new data'}]  

  //results:
  //[{id: 1, text: 'abc'}, {id: 2, text: 'abcd'}]
  //same outdated results of first call
}

getMyPromise(){
 this.promise
 .then(data=>console.log(data)) //here i log my results in console
 .catch(e=>console.log(e))
}

当我的组件启动时,promise 会通过我的内容正常解决,但是如果我使用Update now! 按钮中的update 函数再次调用我的promise,在我的后端数据更新后,promise 会返回相同的结果首次致电ngOnInit()

如何使用相同的 Promise 在我的后端调用更新的数据?这可能吗?

【问题讨论】:

  • 一般来说yes你可以解决一个已解决的承诺,但在这种情况下,我不认为你正在将Observable转换为Promise,但坚持下去我会尝试出来
  • 不,您无法解决已解决的承诺。这样做不会引发异常,但也不会产生任何可观察到的效果。

标签: javascript angular typescript promise


【解决方案1】:

Promise 是一种单向状态机,因此一旦解决,它将永远保持这种状态。你无法改变这一点。只有当它处于pending 状态时,才能用值解析它。尝试在不处于 pending 状态的 Promise 上再次调用 resolve() 只会忽略调用(什么都不做)。

如何使用相同的承诺在我的后端调用更新的数据?这可能吗?

你需要再次调用你原来的异步操作:

this.httpClient.get<any>('http://localhost').toPromise()

获取与新异步操作相关联的新承诺,以获取新数据。这个新的承诺将通过新数据解决。

【讨论】:

    【解决方案2】:

    您总是得到相同的结果,因为您不再调用服务器。

    为了让您的代码按预期工作,您需要实现更多这样的代码行:

    parent.component.ts

    public mypromise;
        ngOnInit() {
         mypromise = this.getSomethig();
        }
    
        public function getSomething() {
         return this.httpClient.get<any>('http://localhost').toPromise();
        }
    

    child.component.ts

    @Input() promise: Promise<any>
    @Output() getSomething = new EventEmitter<any>();
    
    ngOnInit(){
     this.promise
     .then(data=>console.log(data)) //here i log my results in console
     .catch(e=>console.log(e))
    
     //results:
     //[{id: 1, text: 'abc'}, {id: 2, text: 'abcd'}]  
    }
    
    update(){
         this.getSomething.emit();
    }
    

    https://dzone.com/articles/understanding-output-and-eventemitter-in-angular中查看有关事件发射器的更多信息

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-20
      • 1970-01-01
      • 1970-01-01
      • 2016-01-18
      相关资源
      最近更新 更多