http provider Observable.toPromise() not working as expected in promise chains

…衆ロ難τιáo~ 提交于 2019-12-14 03:47:28

问题


If i call a promise enabled method using the ng2 http provider Observable.toPromise() support it works as expected but when i use it as part of promise chain it resolves the returned promise before the then handler has processed and returned the result.

Any known issues with getting Observable.toPromise() to work in promise chains or alternative ways i might test to make it a promise chain compatible result? I'm blocked by this resolving promise before the http request, last item in promise chain, has completed its async request and returned result.

For example

this.myService.getSomethingInvolvingingMultiplePromiseCalls().then(result => {
    let valueFromSomethingInvolvingMultiplePromiseCalls = result;
}, err => { 
    console.error('landed in app.component outer promise rejected handler, see output window for details')
})

public getSomethingInvolvingingMultiplePromiseCalls(): Promise<string> {
    return this.getSomethingInvolvingPromiseCall().then(resultPromise1 => {
        let resultPromise1propertyFoo = resultPromise1.propertyFoo;
            return this.getSomethingInvolvingNg2HttpProviderToPromiseCall(resultPromise1propertyFoo);
        }
        .then(resultPromise2 => {
            let resultPromise2propertyBar = resultPromise2.propertyBar;
            return resultPromise2propertyBar;
        }   
    }

getSomethingInvolvingNg2HttpProviderToPromiseCall(arg1: string): Promise<string> {
   let body = 'some body content leveraging arg1';
   let headers = new Headers({ 'Authorization': 'Bearer ' + accessToken, 'Content-Type': 'application/x-www-form-urlencoded' });
   let options = new RequestOptions({ headers: headers });

   return this.http.post(resourceBaseAddress + '/someRestApi', body, options).toPromise().then(response => {
        let responseJson = response.json();
        return responseJson['someJsonProperty'];
      });
    }
}

thanks in advance for any insights or suggestions.


回答1:


I found a resolution to this.

It involved creating and returning a typescript deferred promise that I control resolving only when I landed inside of then handler for call to method using angular2 http provider toPromise().

Something I didn't have to do with other promise chaining scenarios but for whatever reason in this case allowed by to park method caller until the http provider toPromise() call in the chain completed.

public getSomethingInvolvingingMultiplePromiseCalls(): Promise<string> {
    let resolveFn, rejectFn;
    let promise = new Promise((resolve, reject) => { resolveFn = resolve; rejectFn = reject; });

    this.getSomethingInvolvingPromiseCall().then(resultPromise1 => {
        this.getSomethingInvolvingNg2HttpProviderToPromiseCall(resultPromise1).then(resultPromise2 => resolveFn(resultPromise2));
    }

    return promise;  // return the promise for outside callers to wait on
}



回答2:


See the below working example of an observable in a promise chain.

var promise = new Promise((resolve, reject) => {
  resolve(3)
}).then((num) => {
  return Rx.Observable.create((observer) => {
    setTimeout(() => {
      observer.next(5);
      observer.onCompleted();
    }, 0)
  }).toPromise()
}).then((num) => {
  return num * 2;
})

promise.then((number) => {
  alert(number);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.0.7/rx.all.js"></script>

One gotcha if your using .toPromise() is that observer.onCompleted() must be called. If your converting an observable that does not complete your promise will not resolve.



来源:https://stackoverflow.com/questions/35529245/http-provider-observable-topromise-not-working-as-expected-in-promise-chains

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!