- 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); });
- 軟件安全技術(shù)
- 數(shù)據(jù)庫系統(tǒng)原理及MySQL應(yīng)用教程(第2版)
- Learning Spring 5.0
- Java入門很輕松(微課超值版)
- 算法大爆炸:面試通關(guān)步步為營
- 機(jī)器人Python青少年編程開發(fā)實例
- C語言程序設(shè)計實踐教程
- Web全棧工程師的自我修養(yǎng)
- Functional Kotlin
- 零基礎(chǔ)入門學(xué)習(xí)Python(第2版)
- Access 2010數(shù)據(jù)庫應(yīng)用技術(shù)實驗指導(dǎo)與習(xí)題選解(第2版)
- Natural Language Processing with Python Quick Start Guide
- Sails.js Essentials
- Visual Basic程序設(shè)計全程指南
- 安卓工程師教你玩轉(zhuǎn)Android