Now in .then
section I all another promise http request:
.then(result => { this.service().then(data => {}); });
Is it a correct way to use chained promises?
Now in .then
section I all another promise http request:
.then(result => { this.service().then(data => {}); });
Is it a correct way to use chained promises?
Almost! You need to return the promise in the function, either like this:
.then(result => { return this.service().then(data => {}); });
or like this:
.then(result => this.service().then(data => {}));
Since you are using Typescript, you could use async/await
to chain promises in a more readable way:
function firstCall(): Promise<any> { /* return a promise */ }
function service(): Promise<any>{ /* return a promise */ }
async function runPromisses() {
var result = await firstCall();
var data = await service();
// ...
}
Yes, your two promises are resolved sequentially. But remember that your second (the inner) promise will only be called when the first then was successfully resolved.
An even cleaner solution would be:
.then(result => this.service()).then(data => {});
As elaborated in this SO answer by Hrishi, returning a "thenable" (for example a Promise) inside your then()
function, makes the old promise adopt the state of the new promise.