Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a good example of lodash's _.after method

Is there a good practical example of how to use _.after method in lodash library?

like image 809
BlueLion Avatar asked Mar 15 '23 23:03

BlueLion


1 Answers

Use it whenever you need to invoke a callback after it's been called n number of times.

var fn = _.after(3, function () {
  console.log('done');
});

fn(); // Nothing
fn(); // Nothing
fn(); // Prints "done"

It's useful for invoking callback when all async calls are complete.

  var done = _.after(3, function () {
      console.log('all 3 requests done!');
    });

  $.get('https://example.com', done);
  $.get('https://example.com', done);
  $.get('https://example.com', done);

Basic game example where player dies after getting shot 3 times.

 var isDead = _.after(3, function () {
      console.log('Player died!');
    });

  player1.shoot(player2, isDead); // undefined
  player1.shoot(player2, isDead); // undefined
  player1.shoot(player2, isDead); // "Player died!"

Basically you use _.after in place of a manual counter.

like image 66
Miguel Mota Avatar answered Mar 24 '23 11:03

Miguel Mota