Home  >  Article  >  Web Front-end  >  Promise object in Angular ($q introduction)_AngularJS

Promise object in Angular ($q introduction)_AngularJS

WBOY
WBOYOriginal
2016-05-16 16:11:351490browse

When I was using JQuery, I knew that promise is a JS asynchronous programming model, but I didn’t quite understand the difference between it and JQuery’s deferred object. As the company's project progressed, we needed to receive data from the backend, so we decided to get it done.

Promise

Promise is a mode that operates asynchronous events in the form of a synchronous operation process, avoiding layers of nesting, and can operate asynchronous events in a chain.

We know that when writing JavaScript asynchronous code, callback is the simplest mechanism. However, using this mechanism must sacrifice control flow, exception handling and function semantics, and may even cause us to fall into the trap of callback. pit, and promise solves this problem.

Promise in ES6, AngularJS built-in Q built into angularJS, and when adopt the Promises/A specification, as follows:

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

1.pending status: can transition to fulfillment or rejection status.
2. Fulfilled state: It cannot be changed to any other state, and the state cannot be changed. It must have a value.
3. Rejected state: It cannot be changed to any other state, and the state cannot be changed. There must be a reason.

The state transfer is one-time. Once the state becomes fulfilled (completed) or failed (failed/rejected), it cannot be changed again.

Copy code 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 model changes
$scope.$apply(function() {
              deferred.notify('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);
});

Basic usage of Q Promise

The above code shows the role of several methods of the deffered instance constructed by $q.defer(). If the asynchronous operation succeeds, use the resolve method to change the status of the Promise object to "success" (that is, from pending to resolved); if the asynchronous operation fails, use the reject method to change the status to "failed" (that is, from pending to resolved). rejected). Finally, deferred.promise is returned, and we can call the then method in a chain.

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

$q.defferd in AngularJs

Call $q.defferd to return the deffered object to chain calls. This object associates the three task states in the Promises/A specification through the API.

deffered API

Methods of deffered objects

1.resolve(value): At the declaration of resolve(), it indicates that the promise object changes from the pending state to resolve.
2.reject(reason): At the declaration of resolve(), it indicates that the promise object changes from pending state to rejected.
3.notify(value): When notify() is declared, it indicates the unfulfilled state of the promise object and can be called multiple times before resolve or reject.

deffered object properties

promise: What is finally returned is a new deferred object promise attribute, not the original deferred object. This new Promise object can only observe the state of the original Promise object, and cannot modify the internal state of the deferred object to prevent the task state from being modified 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 interested part to obtain its execution results when the deferred task is completed.

Promise object methods

1.then(errorHandler, fulfilledHandler, progressHandler): The then method is used to monitor the different states of a Promise. The errorHandler monitors the failed status, the fulfilledHandler monitors the fulfilled status, and the progressHandler monitors the unfulfilled (incomplete) status. Additionally, the notify callback may be called zero to more times, providing an indication of progress before resolving or rejecting (resolve and rejected).
2.catch(errorCallback) - shortcut for promise.then(null, errorCallback)
3.finally(callback) - allows you to observe whether a promise is executed or rejected, but does so without modifying the final value. This can be used to do some work of releasing resources or cleaning up unused objects, regardless of whether the promise is rejected or resolved. For more information, see the full documentation specification.

Promise chain calls can be implemented through the then() method.

Copy code The code is as follows:

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

// promiseB will be processed immediately after promiseA is processed,
// And its value value is the result of promiseA increased by 1

Other methods of $q

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn