- Mastering JavaScript Promises
- Muzzamil Hussain
- 462字
- 2021-07-16 13:46:50
Common sequencing patterns
Promise and deferred enables us to represent simple tasks combined with complex tasks to a fine-grained control over their sequences.
As mentioned earlier, deferred is an object that represents work that is not being done yet and promise is an object representing a value that is currently unknown. This concept helps us write asynchronous JavaScript, similar to how we write synchronous code.
Promises make it comparatively easy to abstract small pieces of functionality shared across multiple asynchronous tasks. Let's take a look at the most common sequencing patterns that promises makes easier:
- Stacked
- Parallel
- Sequential
Stacked
Stacked binds multiple handlers anywhere in the application to the same promise event. This helps us bind a number of handlers in a cleaner way so that it gives control to sequence within our code. Here is a sample for stacked and bind handlers:
var req = $.ajax(url); req.done(function () { console.log('your assigned Request has been completed'); }); //Somewhere in the application req.done(function (retrievedData) { $('#contentPlaceholder').html(retrievedData); });
Parallel
Parallel simply asks multiple promises to return a single promise, which alerts of their multiple completion.
With the parallel sequence, you can write multiple promises to return a single promise. In a parallel sequence, an array of asynchronous tasks are executed concurrently and return a single promise when all the tasks have succeeded or rejected with an error in case of failure.
A general code snippet that shows how parallel sequence returns a single promise is shown as follows:
$.when(task01, task02).done(function () { console.log('taskOne and taskTwo were finished'); });
For a more clear understanding, here is a sample function that processes the parallel sequence:
function testPromiseParallelSequence(tasks) { var results = []; //an array of async tasks //tasks.map() will map all the return call was made. taskPromises = tasks.map(function(task) { return task(); }); //returning all the promise
Sequential
Actions need to be in sequence if the output of one action is an input to another. HTTP requests are such a case where one action is an input to the other. Sequence also enables you to transfer the control of one part of the code to the other.
It executes tasks in a sequential order that is defined by the need of the application, or the scope of the tasks that need to be queued in order to be served.
Here is a generic example in which one sequence processes and passes control to the other as an input:
// seq1 and seq2 represents sequence one and two respectively var seq1, seq2, url; url = 'http://sampleurl.com; seq1 = $.ajax(url); seq2 = seq1.then( function (data) { var def = new $.Deferred(); setTimeout(function () { console.log('Request completed'); def.resolve(); },1000); return def.promise(); }, function (err) { console.log('sequence 1 failed: Ajax request'); } ); seq2.done(function () { console.log('Sequence completed') setTimeout("console.log('end')",500); });
- 演進(jìn)式架構(gòu)(原書第2版)
- 工程軟件開發(fā)技術(shù)基礎(chǔ)
- Docker進(jìn)階與實(shí)戰(zhàn)
- 正則表達(dá)式經(jīng)典實(shí)例(第2版)
- Python面向?qū)ο缶幊蹋簶?gòu)建游戲和GUI
- 全棧自動(dòng)化測試實(shí)戰(zhàn):基于TestNG、HttpClient、Selenium和Appium
- Oracle GoldenGate 12c Implementer's Guide
- Visualforce Developer’s guide
- Machine Learning for Developers
- NGUI for Unity
- 官方 Scratch 3.0 編程趣味卡:讓孩子們愛上編程(全彩)
- 金融商業(yè)數(shù)據(jù)分析:基于Python和SAS
- INSTANT EaselJS Starter
- Learning ROS for Robotics Programming
- PHP典型模塊與項(xiàng)目實(shí)戰(zhàn)大全