最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What is the HTTP promise object in AngularJS? - Stack Overflow

programmeradmin8浏览0评论

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?

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?

Share Improve this question edited Nov 20, 2016 at 19:26 Bergi 665k160 gold badges1k silver badges1.5k bronze badges asked Nov 20, 2016 at 14:51 TanvirArjelTanvirArjel 32.1k14 gold badges85 silver badges119 bronze badges 2
  • Thanks!! Would be great if you explain in detail!! – TanvirArjel Commented Nov 20, 2016 at 14:55
  • Do you know what the difference between a "traditional object" and a (generic) promise object is? – Bergi Commented Nov 20, 2016 at 19:26
Add a comment  | 

3 Answers 3

Reset to default 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

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).

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

发布评论

评论列表(0)

  1. 暂无评论