froatsnook:sleep

v2.0.1Published 4 weeks ago

Fiber-friendly/async sleep statements

Meteor 3.0

Meteor 3.0 is on its way and Fibers will no longer work. Instead use await Meteor.sleep(ms) and await Meteor.sleepUntil(date).

Example

On the client, as well as on the server (meteor 3.0 or later), use async/await.

1await Meteor.sleep(1000); // ms
1await Meteor.sleepUntil(new Date(2030, 3, 1));

Meteor 2.x

In versions older than 3.0, you can use Fibers if you're not using async/await yet.

1Meteor.sleep(1000); // ms
1Meteor.sleepUntil(new Date(2030, 3, 1));

Why?

Meteor's fibers Async/await lets 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);

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