The promise of Angularjs notes

Source: Internet
Author: User

Promise is a pattern that operates asynchronous events in the form of a synchronous operation, avoids nesting of layers, and can chain-manipulate asynchronous events.

We know that callback is the simplest mechanism when writing JavaScript async code, but this mechanism must sacrifice control flow, exception handling, and function semantics to the cost, and even let us fall into the callback pit, and promise solves the problem.

ES6 Promise, Angularjs built-in Angularjs built-in Q, and when used are promises/a specifications, as follows:

Each task has three states: incomplete (pending), complete (fulfilled), failure (rejected).

1.pending Status: Can transition to the fulfillment or rejection state.
2.fulfilled Status: Cannot become any other state, and the state cannot be changed, there must be value.
3.rejected Status: Cannot become any other state, and the state cannot be changed, must have reason.

The transition of the state is one-time, and once the state becomes fulfilled (completed) or failed (failed/rejected), it cannot be changed.

function Oktogreet (name) {    return name = = ' Robin Hood ';} function Asyncgreet (name) {    var deferred = $q. Defer (); 
   settimeout (function () {     ///Because this asynchronous function fn is executed asynchronously in the future, we wrap the code into a $apply call, while correctly observing the model change        $scope. $apply ( function () {            deferred.notify (' About to greet ' + name + '. ');             if (Oktogreet (name)) {                deferred.resolve (' Hello, ' + name + '! ');            } else {                deferred.reject (' greeting ' + name + '    is     not allowed. ');}}); return deferred.promise;} var promise = Asyncgreet (' Robin Hood ');p romise.then (function (greeting) {    alert (' Success: ' + greeting);}, function (reason) {    alert (' Failed: ' + reason);}, function (update) {    

  

Basic usage of Q promise

The code above indicates the role of several methods of constructing a deffered instance $q. Defer (). If the asynchronous operation succeeds, the state of the Promise object is changed to "succeeded" (that is, from pending to resolved) using the Resolve method, and if the asynchronous operation fails, the state is changed to "failed" (that is, from reject to pending) with the rejected method. Finally we return to deferred.promise and we can call the then method in a chain.

JS will have native PROMISE,ES6 already have promise object, Firefox and Chrome beta version has implemented the basic promise API

The $q.defferd in Angularjs

by calling the $q. Defferd returns the Deffered object as a chained call. The object associates the three task states in the PROMISES/A specification with an API.

Deffered API

Methods for Deffered objects

1.resolve (value): at declaration resolve (), indicates that the Promise object is transformed from pending state to resolve.
2.reject (reason): at declaration resolve (), indicates that the Promise object is transformed from pending state to rejected.
3.notify (value): at declaration notify (), indicates that the promise object unfulfilled state, which can be called multiple times before resolve or reject.

Deffered Object Properties

Promise: The last returned is a new deferred object Promise property, not the original deferred object. This new promise object can only observe the state of the original Promise object, and cannot modify the intrinsic state of the deferred object to prevent the task State from being externally modified.

Promise API

When you create a deferred instance, a new Promise object is created, and you can get the reference by Deferred.promise.

The purpose of the Promise object is to allow the part of interest to get its execution results when the deferred task completes.

Methods for Promise Objects

1.then (ErrorHandler, Fulfilledhandler, Progresshandler): Then method is used to listen for different states of a promise. ErrorHandler monitoring failed status, Fulfilledhandler monitoring fulfilled status, progresshandler monitoring unfulfilled (not completed) status. Additionally, the notify callback may be called 0 to several times, providing a progress indication before resolving or rejecting (resolve and rejected).
2.catch (errorcallback)--promise.then (NULL, errorcallback) shortcut
3.finally (callback)-allows you to see whether a promise is being executed or rejected, but does not modify the last value value. This can be used to do work that frees up resources or cleans up useless objects, whether promise is rejected or resolved. For more information, see the full documentation specification.

The then () method enables promise chaining calls.

PROMISEB = Promisea.then (function (result) {    return result + 1;  });   PROMISEB will be processed immediately after the Promisea is processed,  //and its value  value is Promisea increased by 1

  

Other ways to $q

$q. When (value): Pass the variable value, Promise.then () executes a successful callback
$q. All (promises): Multiple promise must perform successfully to perform a successful callback, passing a value of an array or hash value, each of which is a promise object corresponding to index

Original: http://www.jb51.net/article/61638.htm

The promise of Angularjs notes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.