Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery promises: Is there a reusable alternative?

I'm building a web app which has a set of functions that the user may perform a few times but involve enough asynchronous actions for callbacks to get a bit out of hand.

What are realistic alternatives to $.Deffered and $.when that can be 'used' multiple times?

  • I'm not looking for a full blown framework
  • I don't want to use callbacks (directly)
like image 299
Haroldo Avatar asked Oct 21 '22 17:10

Haroldo


2 Answers

I think what you're looking for are events. An example in jQuery using on and trigger:

var data_handler = $({});

function get_data(new_foo) {
   // Do stuff, then send the event
   data_handler.trigger('new_data', {foo: new_foo});
}

data_handler.on('new_data', function(e, data) {
   console.log('Handler 1: ' + data.foo);
});

data_handler.on('new_data', function(e, data) {
   console.log('Handler 2: ' + data.foo);
});

get_data(1);
get_data(2);

Output:

Handler 1: 1
Handler 2: 1
Handler 1: 2
Handler 2: 2
like image 71
Izkata Avatar answered Oct 24 '22 09:10

Izkata


Here are 3 such libraries:

  1. Q
  2. rsvp.js
  3. when.js

These libraries are not "full blown". They just implement promises.

like image 24
MegaHit Avatar answered Oct 24 '22 10:10

MegaHit