Promise object in Angular ($ q Introduction)

Source: Internet
Author: User

Promise object in Angular ($ q Introduction)

This article mainly introduces the Promise object in Angular ($ q Introduction). This article describes the Promise mode, the basic usage of Q Promise, and the $ q in AngularJs. defferd and other content. For more information, see

 

 

When using JQuery, we know that promise is a Js asynchronous programming mode, but does not quite understand the difference between it and JQuery's deferred object. As the company's project progresses, it is necessary to connect the data with the background, so it is decided to deal with it.

Promise

Promise is a mode in which asynchronous events are operated in the form of synchronous operations, avoiding layer-by-layer nesting and the asynchronous events can be chained.

We know that callback is the simplest mechanism when writing javascript asynchronous Code. However, to use this mechanism, you must sacrifice the control flow, exception handling, and function semantics, it may even cause us to fall into the callback big hole, and promise solves this problem.

In ES6, Promise, angularJS built-in AngularJS built-in Q, and when adopts Promises/A specifications, as follows:

Each task has three statuses: pending, fulfilled, and rejected ).

1. pending status: the pending status can be transitioned to the fulfillment or rejection status.
2. fulfilled status: the status cannot be changed to any other status, and the status cannot be changed. The value must exist.
3. rejected status: it cannot be changed to any other status, and the status cannot be changed. There must be a reason.

Status transfer is one-time. Once the status changes to fulfilled (completed) or failed (failed/rejected), it cannot be changed again.

 

The Code is as follows:


Function okToGreet (name ){
Return name = 'Robin Hood ';
}

Function asyncGreet (name ){
Var deferred = $ q. defer ();

SetTimeout (function (){
// Because this asynchronous function fn will be executed asynchronously in the future, we wrap the code into the $ apply call, while correctly observing the changes to the model
$ Scope. $ apply (function (){
Deferred. Sort y ('About to greet '+ name + '.');

If (okToGreet (name )){
Deferred. resolve ('hello, '+ name + '! ');
} Else {
Deferred. reject ('greeting '+ name +' is not allowed .');
}
});
},1000 );

Return deferred. promise;
}

Var promise = asyncGreet ('Robin Hood ');
Promise. then (function (greeting ){
Alert ('success: '+ greeting );
}, Function (reason ){
Alert ('failed': '+ reason );
}, Function (update ){
Alert ('got notification: '+ update );
});

 

Q. Basic usage of Promise

The code above indicates the functions of several methods of the deffered instance constructed by $ q. defer. If the asynchronous operation succeeds, use the resolve method to change the state of the Promise object to "successful" (I .e., from pending to resolved). If the asynchronous operation fails, the reject method is used to change the status from pending to rejected ). Finally, deferred. promise is returned. We can call the then method in a chain.

JS will have native Promise, ES6 already has Promise object, firefox and Chrome 32 beta versions have implemented basic Promise API

$ Q. defferd in AngularJs

Call $ q. defferd to return the deffered object for chained call. This object associates the status of three tasks in the Promises/A specification using APIs.

Deffered API

Deffered object Method

1. resolve (value): at the declared resolve (), it indicates that the promise object is changed from pending state to resolve.
2. reject (reason): at the declared resolve (), it indicates that the promise object is changed from pending state to rejected.
3. Define y (value): indicates the unfulfilled state of the promise object at the declared commit y (), which can be called multiple times before resolve or reject.

Deffered Object Attributes

Promise: The last returned result is a new deferred object promise attribute, instead of the original deferred object. This new Promise object can only observe the status of the original Promise object, but cannot modify the internal status of the deferred object to prevent the task status from being changed externally.

Promise API

When a deferred instance is created, a new promise object is created, and the reference can be obtained through deferred. promise.

The purpose of the promise object is to allow the desired part to obtain the execution result when the deferred task is completed.

Promise object Method

1. then (errorHandler, fulfilledHandler, progressHandler): The then method is used to listen to different States of a Promise. ErrorHandler listens to the failed status, fulfilledHandler listens to the fulfilled status, and progressHandler listens to the unfulfilled (unfinished) status. In addition, the notify callback may be called 0 to multiple times, providing a progress indication before resolving or rejecting (resolve and rejected.
2. catch (errorCallback) -- promise. then (null, errorCallback) shortcut
3. finally (callback) -- enables you to observe whether a promise is executed or rejected, but you do not need to modify the final value. This can be used to release resources or clear useless objects, whether the promise is rejected or resolved. For more information, see the full documentation specification.

The then () method can be used to implement the promise chained call.

 

The Code is as follows:


PromiseB = promiseA. then (function (result ){
Return result + 1;
});

// PromiseB will be processed immediately after promiseA is processed,
// And the value of promiseA increases by 1.

 

$ Q other methods

$ Q. when (value): Pass the variable value. Callback for successful execution of promise. then ()
$ Q. all (promises): Multiple promise must be successfully executed before a successful callback can be executed. The passed value is an array or a hash value. Each value in the array is the promise object corresponding to the Index.

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.