This commitment / Delay (promise/deferred) The inspiration for this comes from Kris Kowal's Q CommonJS Promise Suggestion document Will promise (promise) As and Asynchronous execution (action) The interface that the result object interacts with , It may or may not be completed within the specified time ( Such as overtime , error , Intercept and so on ).

From the perspective of error handling , Delay (deferred ) And commitment (promise ) API For asynchronous programming , And synchronous programming try,catch, as well as throw It's about the same .

// For demonstration purposes , Here we assume that `$q`, `scope` as well as `okToGreet` quote Available in the current execution environment 
// ( For example, they have been injected , Or passed in as a parameter ). function asyncGreet(name) {
var deferred = $q.defer(); setTimeout(function() {
// Because of this function Asynchronous execution in future event loops ,
// We need to package the code into a $apply in call , In order to observe correctly model Changes
scope.$apply(function() {
deferred.notify(' About to greet ' + name + '.'); if (okToGreet(name)) {
deferred.resolve(' Hello , ' + name + '!');
} else {
deferred.reject(' Refuse to greet ' + name + ' .');
}, 1000); return deferred.promise;
} var promise = asyncGreet(' Little Momo ');
promise.then(function(greeting) {
alert(' success : ' + greeting);
}, function(reason) {
alert(' Failure bird : ' + reason);
}, function(update) {
alert(' Receive notice : ' + update);

The effect of this extra complexity It may not be obvious at first . stay promise and deferred APIs When you make a commitment, you see the benefits , Please refer to :

Delay interface | Deferred API

By calling $q.defer() You can build a new deffered example .

deffered Object method

  • resolve(value) —— Pass in value Solve the derivative promise. If value It's a pass $q.reject Reject object constructed (rejection) , The promise Will be rejected .
  • reject(reason) —— Reject derived promise, And provide reasons . It's equivalent to passing $q.reject Reject object constructed (rejection) Pass as parameter to resolve.
  • notify(value) —— stay promise Provides status updates during execution . This is in promise It may be called many times before it is resolved or rejected .

deffered Object properties

  • promise – {Promise} —— And delay (deferred) The associated promise object .

When creating a deferred Instance creates a new promise object , And can pass through deferred.promise Get the reference .

promise The object's purpose is to deferred When the task is completed , Allow interested parties to get their execution results .

promise Object method

  • then(successCallback, errorCallback, notifyCallback) —— No matter promise To be dealt with or rejected , Once the results are available ,then Will be called asynchronously as soon as possible success / error Callback function As long as the results are available . Passing a single parameter when calling a callback function : result Or a reason to refuse . Besides ,notify Callbacks may be called 0 To many times , In order to provide Provide a progress indicator , Previously promised to resolve or refuse .

    This method Back to a new promise object , according to successCallback , errorCallback To resolve or reject . It also passes notifyCallback Method . promise Cannot from notifyCallback Methods are resolved or rejected .

  • catch(errorCallback) —— promise.then(null, errorCallback) Shortcut to

  • finally(callback) —— So you can observe a promise To be executed or rejected , But you don't have to change the final value value . This can be used to release resources or clean up useless objects , No matter promise Rejected or settled . For more information, see the full documentation specification .

    Because in ES3 Version of JavaScript in finally Is a reserved word keyword , Cannot be a property name , For adaptation IE8, You need to use promise'finally' Call the method in this form .

promise chain

Because calling a promise Of then Method returns a new derivation promise example , So build promises The chain is also very easy :

promiseB = promiseA.then(function(result) {
return result + 1;
}); // promiseB It will be processed after promiseA And then it's dealt with immediately ,
// And its value The value is promiseA The result of the increase in 1

We can create any length of promise chain ; Because a promise Can be replaced by another promises Handle ( Further delay the completion of the settlement ), So in promise At any point on the chain Pause / Put off solving It's all possible . This makes it possible to achieve powerful APIs Become reality , for example $http Response interceptors for .

Kris Kowal's Q And $q The difference between

  • Angular Medium $q Integrated ng.$rootScope.Scope Scope Model observation mechanism , This means that models It's going to be faster to resolve or reject , Avoid unnecessary browser redraws ( It can lead to UI flashing ).
  • Q Than $q Have more features , But the result is an increase in the number of code bytes . $q It's very lightweight , But it contains all the important functions needed for general asynchronous tasks .

it('should simulate promise', inject(function($q, $rootScope) {
var deferred = $q.defer();
var promise = deferred.promise;
var resolvedValue; promise.then(function(value) { resolvedValue = value; });
expect(resolvedValue).toBeUndefined(); // simulation promise Of resolving
// Be careful 'then' function Not synchronously called .
// Because we want to promise API It's always asynchronous (async),
// This is true in both synchronous and asynchronous calls .
expect(resolvedValue).toBeUndefined(); // Use $apply() take promise resolution Pass on to 'then' functions .

$q rely on $rootScope

$q Methods

  • all(promises)

    Combine multiple promises For a single promise, In all the input promise After all this is done , Combined promise It will be processed .

    Parameters : promises

    type : Array./Object.

    describe : promises Array or reference of

    return : Promise Returns a single promise, Will be solved with an array / Hash value , Each value corresponds to the same index / The key commitment promise / Hash array . If any commitment is made to address exclusion , The resulting commitment will be rejected Reject the same value .

  • defer()

    Create a Deferral Object represents a future task .

    return Deferred Returns a new instance of Deferred.

  • reject(reason)

    Create a promise. this api It should be used in a promises Refuse in the chain . If you're dealing with promise The last one in the chain promise, You don't need to worry about .

promiseB = promiseA.then(function(result) {
// success: Here you can do something , And then use the original result,
// Or right result To operate , To deal with the next promiseB
return result;
}, function(reason) {
// error: handle the error if possible and
// resolve promiseB with newPromiseOrValue,
// Otherwise turn to refuse promiseB The branch of
if (canHandle(reason)) {
// Handling errors and recovery
return newPromiseOrValue;
return $q.reject(reason);

Parameters : reason

type : *

describe : Constant, message, exception Or on behalf of the reason for rejection object.

return : Promise Return to one promise , Because of reason And was rejected .

  • when(value)

    Put an object ( May be value or [ The third party ]then-able promise) Package as a $q promise. This is when you're not sure if the object you're dealing with is a promise It's very useful , It's possible that the object came from an untrusted source .

Parameters : value

type : *

describe : promise Value

return Promise Based on the value passed in / or promise Return a packaged promise

angular Of $q Service and promise More articles on patterns

  1. Angular signal communication $q Service and promise object

    promise Appointment (promise) It's an object , It means something that will happen in the future , An agreement can be one of three states : wait for . To complete or reject . The appointment will start from the waiting state , You can then switch to the done or rejected state , Once the agreement is completed or rejected ...

  2. Angular JS Learning notes ( Custom service :factory,Promise Pattern asynchronous request query :$http, Filter usage filter, Instructions :directive)

    It's not long since I started learning , Did a little project APP, Wechat enterprise number development and wechat service number development , It uses AngularJS Development , The current project 1.0 The version is over , But the project is purely to catch up , Didn't play AngularJS The greatest effect of , These days, the project ...

  3. AngularJS Medium Promise --- $q Service details

    Let's talk about what is Promise, What is? $q Well .Promise Is an asynchronous processing mode , There are many ways to do it , Like the famous Kris Kwal's Q also JQuery Of Deffered. What is? Promise I've known about ...

  4. angular $q Service usage

    Promise It is a kind of harmony. callback There is a similar but more powerful asynchronous processing mode , There are many ways to implement it , Like the famous Q also JQuery Of Deffered. What is? Promise I've known about Ajax All of us can experience the effect of callback ...

  5. $q service ——angular

    $q It's for angular It's a service of , Just for promise A simplified version of the asynchronous programming pattern , There are more than 200 lines of implementation code without comments in the source code , So let's start with $q Of API. One .defer object ( Delay object ) You can pass $q. ...

  6. Talking about Angular Of $q, defer, promise

    Talking about Angular Of $q, defer, promise Time  2016-01-13 00:28:00   Blog Garden - Original essence area original text ...

  7. angular Asynchronous processing of $q Use (promise)

    Angular Medium promise: Promise It's a way to process values asynchronously . Represents the most Possible return value or exception thrown Before , Closures or callbacks are usually used to respond to asynchronous meaningful data Use promis ...

  8. angular Medium $q Service instance

    For understanding $q service Reference resources : Broad callback Management Like other frameworks , ng Provides a generalized asynchronous callback management mechanism . $http  clothing ...

  9. angular Learning notes ( Twenty-nine )-$q service

    angular Medium $q It's used to handle asynchronous ( The main thing, of course, is http Interactive ~). $q It's using promise Asynchronous programming based on . What is? promise Asynchronous programming ? The most important core of asynchronous programming is callback , Because there are callback functions , That's why ...

Random recommendation

  1. Android be based on mAppWidget Realize hand drawn map ( sixteen )– Handle multiple map objects at a time

    The best way to do this is to pop up a dialog box , List the controls that users have touched . You can do this by OnMapTouchListener To deal with it . Refer to the following code , Realize the above functions : mapWidget.setOnMapTouchL ...

  2. MVC 4 At compile time , Give Way View Also pop up exception

    Preface MVC At compile time , No prompt View Mistakes in , When we publish the project, we will notice the exception one by one , It's a big headache when the project is big , Because every release requires at least 5 minute , Only one exception message was received , If there are too many page exceptions , Recently, for example, I've sorted out ...

  3. Surprise exposure 6.24AppCan Mobile development conference Directory , There are so many gifts on the spot !

    AppCan The mobile developers conference is just around the corner , All exhibitors are ready , Half the sky of the moving circle has come , Live events and gifts to explosions , Please have a look one by one ! In no particular order ,AppCan No bias ! 1. Polar verification The first sliding puzzle verification code . ...

  4. hdu 1222 Wolf and Rabbit

    Problem Description There is a hill with n holes around. The holes are signed from 0 to n-1. A rabbi ...

  5. be based on Redis Online user list solution based on

    Preface : Because of the needs of the project , We need to implement the function of online user list in cluster environment , And rely on the online list to achieve a single user login ( Only one login for the same account ) function : In a stand-alone environment , The implementation of online list can adopt SessionListener To complete ...

  6. About redis Internal data structure

    The biggest feeling , No matter from design or source code ,Redis Try to be as simple as possible , The principles used are also easy to understand . Especially the source code , Simple and easy to read , Truly accomplish clean and clear,  This article uses unstable Branch of the source code as a benchmark , Let's start with the general ...

  7. post plug-in unit

    Share the cattle series , Share the cattle column , Share cattle . In project development ,http Request mode is the most common . How to simulate http What about the request ? There are many ways , have access to httpclient Directly simulate the request , You can also use Firefox post plug-in , This chapter is mainly about ...

  8. QT And opencv( Two ) Turn on camera

    OpenCV Medium VideoCapture Not only can you turn on the video .usb camera , There's a lot to do , For example, reading streaming media files , Webcam , Image sequences, etc . Now I'd like to briefly introduce one in Qt of use VideoCapture Class to turn on the laptop ...

  9. drawrect&layoutsubviews

    drawrect Trigger method : Set up frame setneeddisplay contentmode Set to redraw sizetofit layoutsubviews Trigger method setframe layo ...

  10. learning makefile static model