Racing to get a timeout

By Edgar Aroutiounian, catch me on twitter

Here is a simple and elegant way to say “Run this shell command within a maximum of x seconds”

'use strict';

const spawnAsync = require('@expo/spawn-async');

const with_timeout = async (cmd, args, limit = 20 * 1000) =>
    new Promise((_, reject) =>
      setTimeout(() => reject(new Error(`Took longer than ${limit / 1000} seconds`)))
    spawnAsync(cmd, args),

Notice how we don’t need a trailing await for the Promise and the usage of Promise.race.

Check out our forums for more discussions, and if you like what you read, then join iterate hackerspace for a community of programmers in Yerevan for coding workshops, coding community.

Comments powered by Talkyard.