JavaNovice
JavaNovice

Reputation: 1142

Angular JS $http promise object -- How does it work?

All, I'm a beginner to Angular framework and have been reading $http service. I thought I understood Promise object in Angular JS until the below questions popped up my mind. Can you please help me understand?

– When I make a REST call from Angular, Angular work not make the rest call before it executes the other steps in the js from where the REST API is invoked. This is because it’s single threaded. Okay I get this. So when does it execute the REST call? May be after all the instructions in the current JS are done? If yes,

If $http service executes the REST API asynchronously as soon as it sees it,

Thanks much for your help!

Prem

Upvotes: 1

Views: 112

Answers (2)

Ankur Jain
Ankur Jain

Reputation: 16

First of all, it wont block the execution, it sends the request immediately. Basically it follow the promise pattern which uses the concept of callback function. So whenever API returns the response it calls the callback function and resume the process.

There is no concept like second thread. When HTTP return the response the execution doesn't stop. it just call its callback method and after that excute the remaining line of code

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691913

When I make a REST call from Angular, Angular work not make the rest call before it executes the other steps in the js from where the REST API is invoked

No. That is incorrect. It sends the request immediately. But it doesn't block until the response comes back, because that could take a whole lot of time and completely freezes the application. So instead, it registers a callback, and this callback will be called, later, when the response is available. That's the principle of asynchronism.

Who spawns the second thread to execute the REST API

There is no second thread.

The easiest way to look at it is to consider that an HTTP response is an event, just like a click or a keypress. All the unique thread does is to wait for the next event and react to it, in a loop.

Upvotes: 1

Related Questions