Keeping Old Readings Out of the Dashboard

The operator sometimes presses Refresh on the Ridge panel twice in a row. The second press should win, because it asked the station later. If Ridge’s radio link is busy, though, the first poll can take 300 ms while a cache answers the second in 50 ms.

A dashboard that swaps a newer reading for an older one without warning is worse than one that shows nothing. Here, you’ll make a slow reply arrive last on purpose and keep the newest reading anyway.

Hold a Reply Until You’re Ready

A delay of 300 ms proves nothing, since a busy machine can shift it. You need replies you deliver by hand. In Python, inside a coroutine, that’s an asyncio future you complete yourself:

Language: Python
reply = asyncio.get_running_loop().create_future()
reply.set_result(12)
print(await reply)

In JavaScript, new Promise() does that job. You pass it a function, and it calls that function at once with a resolve function. Store resolve, and calling it later with a plain value fulfills the promise with that value. console.log() is JavaScript’s print():

Language: JavaScript
let answerPoll;
const reply = new Promise((resolve) => {
  answerPoll = resolve;
});

answerPoll(12);
console.log(await reply);

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.