Wait in generator functions or how to mock a request in ES6

March 16, 2016

Reading time ~1 minute

Testing requests with generator functions ES6 style

I was implementing an async retrier while refactoring some callback hell. And while testing it I realized that there’s a simple way to make your generators wait.

'use strict';

function wait(done) {
  setTimeout(done, 1000);

That’s it. Function above is perfectly yieldable and will suspend your generator.

So in practice your test would look like this.

'use strict';

function wait(time) {
  return function wait(done) {
    setTimeout(done, time);

describe('Retry', () => {
  it('retries 3 failed att', function* times3() {
    // tell mocha to wait longer

    let total = 3;
    function* req() {
      while (true) {
        // our awesome wait function
        yield wait(1000);
        if (total-- === 1) {
          return 'done';
        throw new Error('test');
    const result = yield retry(req, { times: 4 });
    assert.equal(result, 'done');

I use co-mocha for generator tests, hence

function* times3

Wait function also works in Chrome console in case you want to check it out (don’t forget to use strict).

Phoenix On A Raspberry Pi with Exrm

## Intro> Before you read this be sure to look at:>> 1. [Phoenix Advanced Deployment](http://www.phoenixframework.org/docs/advanced-deplo...… Continue reading

XhrHttpRequest Webworker from the function

Published on December 20, 2015