Home >Web Front-end >JS Tutorial >Detailed explanation of Promises_javascript techniques in Javascript and AngularJS
For example, promises are used when the page calls the Google Maps API.
function success(position){ var cords = position.coords; console.log(coords.latitude + coords.longitude); } function error(err){ console.warn(err.code+err.message) } navigator.geolocation.getCurrentPosition(success, error);
■ How to handle multiple asynchronous methods
What if there are many asynchronous methods that need to be executed sequentially? async1(success, failure), async2(success, failure), ...asyncN(success, failure), how to deal with it?
The simplest one might be written like this:
async1(function(){ async2(function(){ ... asyncN(null, null); ... }, null) }, null)
The above code is relatively difficult to maintain.
We can let a notification appear after all asynchronous methods are executed.
var counter = N; function success(){ counter--; if(counter === 0){ alert('done'); } } async1(success); async2(success); ... asyncN(success);
■ What are Promise and Deferred
deferred represents the result of an asynchronous operation, provides an interface for displaying the operation results and status, and provides a promise instance that can obtain the operation result. Deferred can change the operation status.
Promise provides an interface for interacting with related deferreds.
When creating a deferred, it is equivalent to a pending state;
When the resolve method is executed, it is equivalent to a resolved state.
When the reject method is executed, it is equivalent to a rejected state.
We can define a callback function after creating the deferred, and the callback function will start executing after getting the resolved and rejected status prompts. The asynchronous method does not need to know how the callback function operates. It only needs to notify the callback function to start execution after getting the resolved or rejected status.
■ Basic usage
→ Create deferred
var myFirstDeferred = $q.defer();
Here, for the deferred myFirstDeferred, the status is pending. Next, when the asynchronous method is executed successfully, the status becomes resolved. When the asynchronous method fails, the status becomes rejected.
→ Resolve or Reject this dererred
Suppose there is such an asynchronous method: async(success, failure)
async(function(value){ myFirstDeferred.resolve(value); }, function(errorReason){ myFirstDeferred.reject(errorReason); })
In AngularJS, the resolve and reject of $q do not depend on the context, and can be written roughly like this:
async(myFirstDeferred.resolve, myFirstDeferred.reject);
→ Use promise in deferred
var myFirstPromise = myFirstDeferred.promise; myFirstPromise .then(function(data){ }, function(error){ })
deferred can have multiple promises.
var anotherDeferred = $q.defer(); anotherDeferred.promise .then(function(data){ },function(error){ }) //调用异步方法 async(anotherDeferred.resolve, anotherDeferred.reject); anotherDeferred.promise .then(function(data){ }, function(error){ })
Above, if the asynchronous method async is executed successfully, both success methods will be called.
→ Usually wrap asynchronous methods into a function
function getData(){ var deferred = $q.defer(); async(deferred.resolve,deferred.reject); return deferred.promise; } //deferred的promise属性记录了达到resolved, reject状态所需要执行的success和error方法 var dataPromise = getData(); dataPromise .then(function(data){ console.log('success'); }, function(error){ console.log('error'); })
How to write if you only focus on the success callback function?
dataPromise .then(function(data){ console.log('success'); })
How to write if you only focus on the error callback function?
dataPromise .then(null, function(error){ console.log('error'); }) 或 dataPromise.catch(function(error){ console.log('error'); })
What if the callback returns the same result regardless of success or failure?
var finalCallback = function(){ console.log('不管回调成功或失败都返回这个结果'); }
dataPromise.then(finalCallback, finalCallback);
or
dataPromise.finally(finalCallback);
■ Value chain
Suppose there is an asynchronous method that returns a value using deferred.resolve.
function async(value){ var deferred = $q.defer(); var result = value / 2; deferred.resolve(result); return deferred.promise; }
Since what is returned is a promise, we can continue then and then.
var promise = async(8) .then(function(x){ return x+1; }) .then(function(x){ return x*2; }) promise.then(function(x){ console.log(x); })
Above, the value from resolve becomes the actual parameter of each chain.
■ Promise chaining
function async1(value){ var deferred = $q.defer(); var result = value * 2; deferred.resolve(result); return deferred.promise; } function async2(value){ var deferred = $q.defer(); var result = value + 1; deferred.resolve(result); return deferred.promise; } var promise = async1(10) .then(function(x){ return async2(x); }) promise.then(function(x){ console.log(x); })
Of course a more readable way to write it is:
function logValue(value){ console.log(value); } async1(10) .then(async2) .then(logValue);
The return value of the async1 method becomes the actual parameter in the success method in the then method.
From the perspective of catching exceptions, you can also write like this:
async1() .then(async2) .then(async3) .catch(handleReject) .finally(freeResources);
■ $q.reject(reason)
Using this method can make the deferred appear in error state and give a reason for the error.
var promise = async().then(function(value){ if(true){ return value; } else { return $q.reject('value is not satisfied'); } })
■ $q.when(value)
Return a promise with value.
function getDataFromBackend(query){ var data = searchInCache(query); if(data){ return $q.when(data); } else { reutrn makeAasyncBackendCall(query); } }
■ $q.all(promisesArr)
Wait for all promises to be executed.
var allPromise = $q.all([ async1(), async2(), ... asyncN(); ]) allProise.then(function(values){ var value1 = values[0], value2 = values[1], ... valueN = values[N]; console.log('all done'); })
The above is the detailed content of this article. I hope it will be helpful to everyone’s study. Happy New Year!