TanvirArjel TanvirArjel - 18 days ago 5
AngularJS Question

What is the HTTP promise object in AngularJS?

Although I am working with the HTTP promise object in AngularJS, I don't have a clear concept of what an HTTP promise object actually is and what the is difference between an HTTP promise object and a traditional object in AngularJS!

Would anybody explain this, please?

Answer

A Promise is a concept for asynchronous operations. Basically it represents an object that can be available at any point from now into the future.

It has three states:

  • Pending
  • Fulfilled (it completed successfully)
  • Rejected (it failed)

You handle the states of your Promise with two methods, then() and catch().

then() returns the object from your asynchronous call if successfully, and catch() will allow you to handle an error.

A scenario where you might use a Promise is when you're making a network call, for example:

getData(): Promise<Array<string>> {
    this.http.get("http://a-test-api.com/api/getdata").toPromise();
}

You'd then use it like this:

this.getData().then(function (stringArray) {
        self.data = stringArray;
});

You can find some more information on the concept here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise