Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support for async callback #81

Closed
francescoagati opened this issue Feb 14, 2013 · 5 comments
Closed

support for async callback #81

francescoagati opened this issue Feb 14, 2013 · 5 comments

Comments

@francescoagati
Copy link

Hi,
there is a callback for async callback in map and other functions?

for example

$().ready(function () {
    $(".ss").asEventStream("click").map(function(e,cb) {
      setTimeout(function() {
          cb(5000)
       },1000);
    }).log();
});

function log should write 5000

@lautis
Copy link
Member

lautis commented Feb 14, 2013

You'll need to wrap your async callback as Bacon EventStream and then you can use flatMap to achieve this. FlatMap maps an event to a EventStream and merges the created streams to result stream.

$(".ss").asEventStream("click").flatMap(function(e) {
  return Bacon.later(1000, 5000);
});

There isn't a direct method to wrap callbacks, but if you're dealing with AJAX, Bacon.fromPromise can be used. If nothing else, you can always use a Bus.

stream.flatMap(function(e) {
  var bus = new Bacon.Bus()
  setTimeout(function() {
    bus.push(5000);
    bus.end()
  },1000);
  return bus;
});

@raimohanska
Copy link
Contributor

@lautis thanks! Nice solution.

An even simpler solution to this particular problem would be

$(".ss").asEventStream("click").map(5000).delay(1000)

The flatMap solution is more flexible though. (Have a look at the implementation to delay to find out it actually just wraps your solution)

Would it make sense to include an easy callback wrapper API? If it existed, how would you like your client code to look like?

@raimohanska
Copy link
Contributor

In fact, there is Bacon.fromCallback().

$(".ss").asEventStream("click").flatMap(function(v) {
  return Bacon.fromCallback(function(callback) {
    setTimeout(function() {
      callback(5000)
    }, 1000)
  })
})

Looks clumsy, of course, compared to the specific solution using delay.

@lautis
Copy link
Member

lautis commented Feb 14, 2013

Oh, cool. That's what I imagined the API for fromCallback to be. It's handy if you need to wrap a third party library to a Bacon stream (e.g. Zepto.js AJAX, which doesn't use promises).

@francescoagati
Copy link
Author

thanks it really work like i want

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants