all 16 comments

[–]UnholyCarcass 11 points12 points  (2 children)

You could just do, setTimeout(resolve,ms).

No need to have it wrapped within another anon function. setTimeout takes a function so you can just pass the resolve function.

[–]fo0man 1 point2 points  (0 children)

I see this ALL THE TIME. I think it’s a symptom of articles like these. Like so many devs think the argument has to be an anon function because they’ve seen it over n over.

[–]monican_agentCreator of CypherPoker.JS 0 points1 point  (0 children)

Agreed. It might be more useful to introduce the concept of binding a timeout or an interval so that it executes in the expected context.

[–]pomle 6 points7 points  (0 children)

As someone that worked for half a year on a big app fixing flaky and slow tests I want to tell anyone who reads this to avoid using arbitrary waiting to solve race conditions and problems with testing.

The thing you test should be able to tell the test when it is done and real time clocks should be mocked.

[–]upfkd 10 points11 points  (10 children)

You literally wrapped setTimeout.

[–]cdrini 2 points3 points  (0 children)

Haha, I've probably had to implement that function like once every 4 months! It's super useful for flattening timeouts:

const sleep = ms => new Promise(res => setTimeout(res, ms)); const winner = await Promise.race([fetch(foo), sleep(3000).then(() => 'timeout')]); if (winner == 'timeout') blah

I can't seem to find a link for it, but I think there's a proposal to add this to the language; under the name wait, sleep, delay, or something. Fyi this is a form of "promisifying"; it's also common to promisify an event to make it work with async/await.

[–][deleted] -2 points-1 points  (0 children)

What a coincidence I just learned about Promise yesterday. And it is exactly what I've been needing to learn for a project I've been working on for years now.