Developing on Staxmanade

Easily simulate slow async calls using JavaScript async/await

(Comments)

Recently I wanted to manually and visually test some U.I. that I couldn't easily see because an async operations was happening two fast. (first world problems)

I've really been enjoying the new async/await syntax that can be leveraged in recent JavaScript transpires such as Babel and TypeScript but when it happens so fast on a local development environment, some U.I. interactions could get tough to test out. So how can we slow this down or more appropriately add some stall time?

As an example, let's say you have the following async javascript method


var doSomething = async () => {
  var data = await someRemoteOperation();
  await doSomethingElse(data);
}

If the first or second asynchronous methods in the example above were running too fast (as were in my case), I was pleased to see how easy it was to inject a bit of code to manually stall the operation.

The snippet below is short and sweet... this just delays continuous execution of an async operation for 3 seconds.

  await new Promise(resolve => setTimeout(resolve, 3000));

The little baby staller helper

Give it a name and make it a bit more re-usable.

async function stall(stallTime = 3000) {
  await new Promise(resolve => setTimeout(resolve, stallTime));
}

The above helper can be used by just awaiting it (see below)


var doSomething = async () => {

  var data = await someRemoteOperation();

  await stall(); // stalls for the default 3 seconds
  await stall(500); // stalls for 1/2 a second

  await doSomethingElse(data);

}

Now we have an async function that runs slower - isn't that what you always wanted?

Happy Stalling!

Comments