What is the HTTP promise object in AngularJS?
Asked Answered
I

3

12

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?

Inosculate answered 20/11, 2016 at 14:51 Comment(2)
Thanks!! Would be great if you explain in detail!!Inosculate
Do you know what the difference between a "traditional object" and a (generic) promise object is?Halfbound
G
12

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() provides you with the expected object from your asynchronous call if successful, and catch() will allow you to handle the error.

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

getData(): Promise<Array<string>> {
    return 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

Graiggrail answered 20/11, 2016 at 14:56 Comment(2)
I think you're missing a return in getData?Fatuous
"then() returns the object from your asynchronous call" - nope.Halfbound
S
4

Promises are a concept. This is a question on AngularJS Promises, which are a bit different from other promises, but the concept across libraries are fundamentally the same.

What are Asynchronous Processes?

If you know what this is, skip it and read the next header, otherwise:

When you have code, it generally runs in sequential order like so:

object.method() // First,
variable = "something"; // Second,
for(var i=0; i<2; i++) {
    resp = object.makeHttpRequest();
    console.log(resp.data + " was #" + i);
} // Third,
console.log("Done"); // Last.

Each step is performed after the previous finishes. This can be a problem when that for loop takes a long time (imagine the HTTP request takes a long time). The request would hang an entire process until the HTTP request is finished. Very bad.

Node.js handles this by default using a callback pattern. When you call a function that is blocking (takes a long time, like reading a file on disk or making an HTTP request), you register a callback function it will call after finishing. It will apply the function with the data from the blocking function when it finishes. This allows you to run other code while that blocking function finishes.

As many Node.js developers will tell you, this code can get very messy, very fast. Instead, AngularJS (and other libraries) will return you a Promise for when the code will finish. It allows you to use a Promise Pattern.

I know what asynchronous stuff is

Promises are conceptually similar to callbacks, but much cleaner and allow a greater degree of control. Consider this:

var url = getUrlFunction();
makeHttpRequest(url, function onResponse(data) {
    dataHandler(data);
    console.log("done");
}, function onError(err) {
    errHandler(err);
    console.log("uh oh");
});
showTheUserWeAreLoading();

// Or in node.js

var url = getUrlFunction();
makeHttpRequest(url, function onResponse(err, data) {
    (err) ? handleErr(err): null;
    dataHandler(data);
    console.log("done");
});
showTheUserWeAreLoading();

It is not very intuitive that the showTheUserWeAreLoading function will (sometimes) happen before the HTTP request if fulfilled. This leaves much to be desired when rereading your own code.

The same code, but with the makeHttpRequest returns a promise:

var url = getUrlFunction(), prom = makeHttpRequest(url);
showTheUserWeAreLoading();
prom.then(function onSuccess(data) {
    dataHandler(data);
    console.log("done");
}, function onError(err) {
    errHandler(err);
    console.log("uh oh");
});

The promise object helps track the state of the operation. You assign handlers for when the operations reaches one of two states: Fulfilled or Rejected.

It should be noted that makeHttpRequest is a stand-in for $http() in AngularJS or $.ajax in jQuery. Before the standard for promises was created in the ECMAScript standard, each library (and library version) had its own opinion on which pattern you should/can use. AngularJS previously used the .success(<function>).error(<function>) naming pattern, while jQuery used .done(<function>).fail(<function>). These naming schemes have been depreciated a very long time ago, therefore making the current difference between libraries unnoticeable (thank you ECMAScript).

Scientism answered 20/11, 2016 at 15:36 Comment(3)
OK, so you explain what promises are (we already have questions on that), but what is the difference to AngularJS promises that you mentioned, and what is the difference to http promises that the OP asked about?Halfbound
Before, the promise object returned had no standard on what had to be returned. In jQuery 1.5-7, the promise would be called back with .done and AngularJS would use .success for their callback. This was later standardized to .then in order to make promises more consistent across libraries (and for future browser implementation.Scientism
That still doesn't answer the question.Halfbound
D
1

The $http API is based on the deferred/promise APIs exposed by the $q service.

1.then(successCallback, [errorCallback], [notifyCallback])

2.catch(errorCallback) – shorthand for promise.then(null, errorCallback)

3.finally(callback, notifyCallback)

$q promise method

Dopey answered 20/11, 2016 at 15:3 Comment(1)
Thanks code of @Hardik Vaghani and review from others, I learn a lot from it.Cantara

© 2022 - 2024 — McMap. All rights reserved.