- Mastering JavaScript Promises
- Muzzamil Hussain
- 327字
- 2021-07-16 13:46:50
Decoupling events and applications logic
Promises provide an efficient way to decouple the events and application logic. This makes the implementation of events and application logic easier to build and maintenance also saleable.
A simple way to show how promises decouple events and business logic
The significance of durability in promises is that it's not an "EventEmitter", but can be converted into one by intelligent implementation. But then again, it would be a crippled one.
Promises as event emitters
The problem in using promises as an event emitter is it's composition. It's the progression events in promises that cannot compose very well with EventEmitter. Promises chain and compose whereas events, on the other hand, are unable to do so. An implementation of Q library is discarding the progression in favor of estimation in v2. This is why progression was never included in ECMAScript 6. We will learn a great deal about a few of these emerging technologies in Chapter 9, JavaScript – The Future Is Now.
Coming back to our topic of how promises is decoupling events and applications logic, we can use events to trigger the resolution/failure of promises by passing the value at the same time, which allows us to decouple. Here is the code:
var def, getData, updateUI, resolvePromise; // The Promise and handler def = new $.Deferred(); updateUI = function (data) { $('p').html('I got the data!'); $('p').html(data); }; getData = $.ajax({ url: '/echo/html/', data: { html: 'testhtml', delay: 3 }, type: 'post' }) .done(function(resp) { return resp; }) .fail(function (error) { throw new Error("Error getting the data"); }); // Event Handler resolvePromise = function (ev) { ev.preventDefault(); def.resolve(ev.type, this); return def.promise(); }; // Bind the Event $(document).on('click', 'button', resolvePromise); def.then(function() { return getData; }) .then(function(data) { updateUI(data); }) .done(function(promiseValue, el) { console.log('The promise was resolved by: ', promiseValue, ' on ', el); }); // Console output: The promise was resolved by: click on <button> </button>
The reference of the following code is available at http://jsfiddle.net/cwebbdesign/NEssP/2.
- R語(yǔ)言數(shù)據(jù)分析從入門(mén)到精通
- Kali Linux Web Penetration Testing Cookbook
- 面向STEM的Scratch創(chuàng)新課程
- x86匯編語(yǔ)言:從實(shí)模式到保護(hù)模式(第2版)
- 64位匯編語(yǔ)言的編程藝術(shù)
- 琢石成器:Windows環(huán)境下32位匯編語(yǔ)言程序設(shè)計(jì)
- Mastering Linux Network Administration
- UVM實(shí)戰(zhàn)
- 編程可以很簡(jiǎn)單
- BeagleBone Robotic Projects(Second Edition)
- PHP與MySQL權(quán)威指南
- 貫通Tomcat開(kāi)發(fā)
- ASP.NET求職寶典
- Go語(yǔ)言入門(mén)經(jīng)典
- SSH框架企業(yè)級(jí)應(yīng)用實(shí)戰(zhàn)