JavaScript in 2024: Awaiting a Calibration Result with Promise.withResolvers
Connect two consumers to one promise for an event-driven measurement. A local example exercises success, device failure, duplicate delivery and cleanup.
Archive retrospective · Topic year 2024
In this article
A calibration console receives its result as an event
Consider a calibration console that shows one pressure probe in a table and in a details pane. Both components need the same result, which arrives later as a message from the device. If calibration fails, the device emits a different event. The caller that wants the result and the message handler that receives it occupy different parts of the application. The ECMAScript 2024 specification includes Promise.withResolvers, which creates a promise together with the functions that will settle it. Our example uses that relationship to share a promise between two views of one probe, settle a separate probe as a failure and discard an extra message. The choices are deliberately visible in the code. Probe identifiers and readings are example data, so the exercise runs locally without external services or a physical calibration device.
Give the consumer a promise and keep the controls private
Promise.withResolvers returns an object containing promise, resolve and reject. The consumer receives the promise. The event handler retains access to the functions that settle it. In this example the record lives in a Map indexed by probe identifier. A second call for P-12 can return the existing promise immediately. That makes two views of a single job consistent without opening another record or starting another device request. The choice of key expresses an assumption about the workflow. Here, a probe has at most one pending calibration. If two jobs for the same probe can overlap, the key must identify the calibration rather than only the probe. Message producers and consumers would then carry a job identifier that is unique in the relevant scope. The rest of the UI can continue to work with a promise alone.
Test two probes and an extra message
The example creates a promise for P-12 and verifies that a second registration yields the very same object. Next it creates a separate wait for P-43 and attaches Promise.allSettled so both outcomes can be inspected together. P-12 receives a reading of 4.8. A later message for P-12 carries a reading of 9.9 and finds no matching record. P-43 produces an error that is exposed as Calibration P-43 failed. The run on Node.js v24.19.0 returned true for the first acceptance, false for duplicateAccepted, and zero for pending after both outcomes were processed. Assertions enforce those outputs. This is a check on the installed Node version. The historical reference is the 2024 edition of the language specification. A browser from that year and actual device firmware were outside the test.
import assert from 'node:assert/strict';
const waiting = new Map();
function waitForCalibration(id) {
const existing = waiting.get(id);
if (existing) return existing.promise;
const deferred = Promise.withResolvers();
waiting.set(id, deferred);
return deferred.promise;
}
function acceptCalibration({ id, ok, reading }) {
const deferred = waiting.get(id);
if (!deferred) return false;
waiting.delete(id);
if (ok) deferred.resolve(reading);
else deferred.reject(new Error(`Calibration ${id} failed`));
return true;
}
const first = waitForCalibration('P-12');
assert.equal(first, waitForCalibration('P-12'));
const second = waitForCalibration('P-43');
const results = Promise.allSettled([first, second]);
const accepted = acceptCalibration({ id: 'P-12', ok: true, reading: 4.8 });
const extra = acceptCalibration({ id: 'P-12', ok: true, reading: 9.9 });
acceptCalibration({ id: 'P-43', ok: false });
const [passed, failed] = await results;
assert.equal(passed.value, 4.8);
assert.equal(failed.reason.message, 'Calibration P-43 failed');
assert.equal(extra, false);
assert.equal(waiting.size, 0);
console.log(JSON.stringify({node:process.version, accepted, reading:passed.value,
rejected:failed.reason.message, duplicateAccepted:extra, pending:waiting.size}));
Remove the completed record when delivering the result
The handler deletes its Map entry before calling resolve or reject. That matters if a result consumer starts another calibration after the old record settles. It should create a new wait instead of reusing the settled promise. The promise itself has one eventual settlement. That property says nothing about how long external application state is kept. The demonstration discards an extra message while there is no waiting record. If a new wait for the same probe were already open, an old message could match it. Use a separate job identifier when the transport allows that ordering. A listener should retain enough context to tell whether an event belongs to live work. The fixture verifies the duplicate case described in the code and leaves transport guarantees to the actual protocol.
Make timeouts and input lifetime explicit
A device might fail to send any message. Promise.withResolvers supplies the settlement functions, so the surrounding application defines when a wait expires. Under a production policy, start a timer when registering a calibration and clear it when a matching result arrives. After an expiry, remove the registry entry and reject with a reason suitable for the interface. A race that only resolves the UI’s timeout can leave a stale entry in the registry. An operator’s cancel action raises a similar question about cleanup. The device may continue the operation after the panel stops waiting. Read back the status before a second operator starts a replacement, or define how late results will be handled when the channel reconnects. This work belongs to the protocol and lifecycle of the device integration.
Observe the boundary between delivery and presentation
The size of the registry and the age of its oldest record are useful signals when an interface appears stalled. You can log the job and probe identities together to diagnose repeated messages without duplicating the whole payload. A trace can show whether a device error, a timeout or a disconnected channel ended the wait. Separating those outcomes matters for an operator who can restart some checks and needs help for others. Promise.allSettled is useful in an inspection or test because it keeps the successful result available even when another job fails. A production view can instead subscribe to the promise assigned to each widget. The example stays small by keeping the side that opens a wait and the side that accepts a reading separate. That boundary makes later changes to the device transport easier to test.
Reader discussion
Which alternative architecture would you try for the same problem?
No comments yet. Be the first to contribute.
Write a comment