froatsnook:sleep

v1.2.0Published 9 years ago

This package has not had recent updates. Please investigate it's current state before committing to using it in your project.

Fiber-friendly/async sleep statements

Example

1console.assert(Meteor.isServer); // Meteor.sleep (without ES7) only works on the server
2Meteor.sleep(1000); // ms
1console.assert(Meteor.isServer); // Meteor.sleepUntil (without ES7) only works on the server
2Meteor.sleepUntil(new Date(2020, 3, 1));

Why?

Meteor's fibers let you wait (i.e. during I/O) without blocking the event loop. But the greatest of all ways to wait has been unattainable until now. This package lets you sprinkle sleep statements throughout your code to convince your boss to buy better hardware. Or to rate-limit your API usage without using setTimeout.

1// Shopify wants no more than two events per second.
2var results = [];
3for (var i = 0; i < numPages; i++) {
4    Meteor.sleep(500);
5
6    var currentPage = FetchOrders(i);
7    results = results.concat(currentPage);
8}
9HandleResults(results);

Now with ES7 support

Have you ever wondered what the best ES7 feature is? Well, the answer is async/await. Here's why:

1console.assert(Meteor.isClient); // Meteor.sleep works on the client with ES7
2async function() {
3    // Do stuff
4
5    // Sleep 2 seconds
6    await Meteor.sleep(2000);
7
8    // Sleep for days
9    await Meteor.sleepUntil(new Date(2020, 3, 1));
10
11    // Do other stuff
12}

In other words, Meteor.sleep also works on the client now. This won't actually work until Meteor 1.3, but prepare yourself.

In a future version it should be possible to use await Meteor.sleep() on the server for a truly isomorphic experience.

Alternatives

The real advantage is code clarity. The following examples demonstrate how this code might be written in the browser (where fibers are not available).

1// plain javascript
2var results = [];
3(function fetcher(i) {
4    if (i === 5) {
5        HandleResults(results);
6        return;
7    }
8
9    var currentPage = FetchOrders(i);
10    results = results.concat(currentPage);
11    Meteor.setTimeout(function() {
12        fetcher(i + 1);
13    }, 500);
14})(0);
1// async.js
2async.concatSeries(_.range(5), function(i, callback) {
3    var currentPage = FetchOrders(i);
4    Meteor.setTimeout(function() {
5        callback(null, currentPage);
6    }, 500);
7}, function(err, results) {
8    HandleResults(results);
9});

Setup

  • Install meteor add froatsnook:sleep

License

MIT