Erudaki Erudaki - 3 months ago 8
HTTP Question

.then handler being invoked out of order

My ultimate goal is to assign a chunk of database to class based object. To do this I am utilizing promises in typescript with the help of the

.then()
function to chain them. However I am running into brick walls.

return(this.httpService.post(someurl, somepayload, someheaders)
.toPromise()
.then(response => response.json())
.then(MyCustomClass.function(MyObject)));


However when this code executes the
.then(MyCustomClass.function(MyObject))
before it gets the
response.json()
which is causing issues in my program.

My question is, why are they occurring in that order and is there any way I can force them to execute in sequence?

Answer

You're calling MyCustomClass.function(MyObject), and passing the returned value to then(). What you actually want is to pass a function that, when called, will execute MyCustomClass.function(MyObject):

.then(() => {
  MyCustomClass.function(MyObject);
}));