Dart / Contracts: patterns, generic APIs, and asynchronous results / Lesson 14
Own Future completion and failure
Await an asynchronous operation, handle a controlled rejection, and define where success may be reported.
On this page
Lesson goals
- Connect a Future to the caller that owns completion.
- Distinguish a successful value from a thrown error.
- Test delayed failure and cleanup at the owning boundary.
- Connect Future completion and failure to an owner before reporting success.
- Test delayed results, cleanup and stale-request handling with controlled fixtures.
Define completion ownership
An asynchronous operation can outlive the statement that starts it. The caller responsible for a result must await or return the corresponding Future so its own completion reflects the work. Decide which layer can recover from an expected failure and which errors should propagate. The examples use synthetic operations without network access; a real dependency also needs a timeout, cancellation, and resource policy appropriate to its API.
Await a successful value
The first program awaits loadCount inside an async main and prints the value only after the Future completes. The try block surrounds the awaited operation, so a thrown asynchronous error reaches the catch. This example catches broadly to display a controlled teaching result; production code should handle only errors it can meaningfully recover from and preserve context for unexpected defects.
Future<int> loadCount() async => 3;
Future<void> main() async {
try {
final count = await loadCount();
print("count: $count");
} catch (error) {
print("load failed: $error");
}
}
The caller awaits the value before printing it.
Observe a controlled failure
The second independent program replaces the operation with one that throws StateError. Awaiting it transfers the error to the surrounding catch, so the success line is not printed. Do not copy both programs into one file unchanged because they define the same names. A real caller should choose an appropriate response or propagate the failure; printing an error and returning normally is a recovery decision.
Future<int> loadCount() async {
throw StateError("unavailable");
}
Future<void> main() async {
try {
final count = await loadCount();
print("count: $count");
} catch (error) {
print("load failed: $error");
}
}
The thrown error reaches the catch around the await instead of the success branch.
Plan cleanup and late work
An awaited failure does not automatically cancel unrelated work or undo a remote side effect. If the operation owns a subscription, file, or other resource, release it in the appropriate finally or lifecycle path. When a user starts a newer request, also prevent an older result from updating current state. Test those ownership rules separately from the simple Future examples.
Verify completion and failure
Use a controlled Future that completes only when the test allows it, and confirm the caller does not announce success early. Complete it successfully, then repeat with a delayed error and verify the documented error path. Test cleanup on both paths and a late result after disposal. Run the examples with the declared Dart SDK; do not infer server-side cancellation from a client-side timeout.
Make the owner’s completion truthful
A Future represents an eventual value or failure. A function that starts consequential work must either await it or return a Future connected to it if its caller is responsible for completion. Reporting success immediately after starting a save can mislead the user while the save is still pending or later fails. A deliberate pending response is different: it names the continuing owner and gives the caller a way to observe the eventual result.
The current function can await when it must transform the result, handle a known failure or run cleanup before reporting completion. Returning a Future can transfer observation to the caller, provided the returned Future actually represents the work. A detached task needs a separate owner, error path and lifecycle; ignoring its Future does not make errors harmless or make work durable.
Handle the awaited failure at the right layer
Place await inside the try that understands the failure. A Future that later completes with StateError transfers that error to a matching handler around the await; the success statement following await is skipped. If the handler returns normally, that is a recovery decision. Catch a narrow expected error when translating it, and rethrow or propagate unexpected defects with safe diagnostic context instead of turning them into a plausible success.
An await observes its particular Future. It does not cancel unrelated Futures, roll back a remote write or guarantee that a timeout stopped the source operation. If a remote write’s result is ambiguous, use the service’s documented status query or stable request-identity and retry contract. Distinguish local waiting, remote completion and product-level success in both code and user feedback.
Include cleanup in the owned lifetime
A resource owner should define cleanup on both success and failure. In an async function, finally can await a documented asynchronous close before the owner completes. A marker printed in finally shows only that statement’s execution; it does not prove an actual resource closed, an external transaction rolled back or a subscription stopped. Check the real resource’s contract and state separately.
Cleanup can itself fail. A return or unrelated exception from finally can replace an earlier result or failure, so decide which error is primary and how to report a secondary cleanup failure. If work succeeded but required cleanup failed, the caller must not silently receive a complete-success claim when the contract requires successful cleanup. Test both paths with controlled local fakes and then verify the real API independently.
Guard late results and disposal
A newer request can finish before an older request. If only the newest result may update a screen, assign a generation or request token when starting work and compare it again before applying the result. This guards local state from a stale completion; it does not cancel the old Future or reverse its external side effects. A disposed owner also needs an explicit rule that prevents later updates to disposed state.
Test these cases using controlled completion rather than relying on arbitrary delays: start request A, start B, complete B, then complete A and check that the screen still reflects B. Separately complete a request after disposal and confirm that no update occurs. A token policy is one approach; cancellation supported by a real API can complement it but must follow that API’s own semantics.
Control completion in a test
A Completer can provide a Future whose completion a local test controls. Attach the observer before completing it, assert that the owner has not reported success while it is pending, then complete with a value and await the owner. A separate test can complete with an error and assert the expected handler and cleanup. Do not complete the same Completer twice; create a new fixture for each case.
These examples are synthetic and their asynchronous outcomes are reasoned from official API semantics. Scheduler-sensitive blocks remain runnable:false unless the exact source is qualified in a controlled environment; no timing, network or cancellation observation is claimed. A passing fake test establishes the tested local contract, not external service availability, durable execution or capacity.
Walk through controlled completion
The caller creates a Completer<int> and starts load, which awaits its Future inside a typed StateError boundary. The caller then completes the synthetic source with 3 and awaits the result. The reasoned result is count:3. A separate fixture could complete with StateError and expect unavailable; the two paths require separate Completers.
The caller does not print a success before awaiting the owner’s result. This example does not contact a provider, test a timer or prove resource cleanup. A production operation should define its actual ownership, failure and cancellation rules; a controlled fake tests only the local coordination logic.
import 'dart:async';
Future<String> load(Completer<int> source) async {
try {
final count = await source.future;
return 'count:$count';
} on StateError {
return 'unavailable';
}
}
Future<void> main() async {
final source = Completer<int>();
final result = load(source);
source.complete(3);
print(await result);
}
count:3
The controlled source supplies 3 and the owner returns count:3; this asynchronous example is unexecuted.
20 worked examples
1. Return the operation Future
Problem: Transfer ownership of a synthetic count to the caller.
- load returns the Future created by read rather than discarding it.
- The caller awaits that returned Future and obtains 4.
Future<int> read() async => 4;
Future<int> load() => read();
Future<void> main() async { print(await load()); }
4
Returning the connected Future allows the caller to observe completion. This asynchronous illustration is reasoned and unexecuted.
Why this result follows: Returning the connected Future allows the caller to observe completion.
2. Await before reporting success
Problem: Wait for a synthetic save result before printing saved.
- save completes successfully with its value.
- The caller awaits it before reaching the saved print.
Future<void> save() async {}
Future<void> main() async {
await save();
print('saved');
}
saved
The success statement follows completion of the owned Future. This asynchronous illustration is reasoned and unexecuted.
Why this result follows: The success statement follows completion of the owned Future.
3. Complete a controlled Future with a value
Problem: Use a Completer to provide a synthetic result after starting the owner.
- The owner awaits the Completer’s Future.
- Completing it with 5 allows the owner to return 5.
import 'dart:async';
Future<void> main() async {
final c = Completer<int>();
final result = c.future;
c.complete(5);
print(await result);
}
5
A controlled Future separates starting work from providing its result. This asynchronous illustration is reasoned and unexecuted.
Why this result follows: A controlled Future separates starting work from providing its result.
4. Complete a controlled Future with an error
Problem: Deliver a synthetic StateError to an awaiting owner.
- The catchError handler is attached to the Completer’s Future before it is completed.
- The synthetic StateError is handled by returning -1, which the caller awaits and prints.
import 'dart:async';
Future<void> main() async {
final c = Completer<int>();
final observed = c.future.catchError((Object e) => -1);
c.completeError(StateError('bad'));
print(await observed);
}
-1
A controlled error tests the failure path without a real service. This asynchronous illustration is reasoned and unexecuted.
Why this result follows: A controlled error tests the failure path without a real service.
5. Do not announce pending work as success
Problem: Trace an owner while a controlled Future remains incomplete.
- The operation has started but the controlled source has not completed.
- The owner cannot truthfully report completed success at that point.
test sequence:
1. start owner with pending Completer
2. assert success has not been reported
3. complete with value
4. await owner and assert success
Starting and completing an operation are separate states. This asynchronous illustration is reasoned and unexecuted.
Expected result: Success is reported only after completion.
Why this result follows: Starting and completing an operation are separate states.
6. Handle a known awaited error
Problem: Translate a controlled StateError to an unavailable result.
- The awaited function completes with StateError.
- The matching handler returns unavailable rather than reaching the count branch.
Future<int> read() async => throw StateError('unavailable');
Future<String> load() async {
try { return 'count:${await read()}'; }
on StateError { return 'unavailable'; }
}
Future<void> main() async { print(await load()); }
unavailable
A typed boundary makes its recovery decision explicit. This asynchronous illustration is reasoned and unexecuted.
Why this result follows: A typed boundary makes its recovery decision explicit.
7. Propagate after partial handling
Problem: Let the caller see a failure after a local diagnostic marker.
- The inner handler catches the awaited StateError and prints observed.
- rethrow passes the same failure to the outer handler, which prints failed.
Future<void> work() async {
try { await Future<void>.error(StateError('bad')); }
on StateError { print('observed'); rethrow; }
}
Future<void> main() async {
try { await work(); } on StateError { print('failed'); }
}
observed
failed
The intermediate layer does not invent a successful value. This asynchronous illustration is reasoned and unexecuted.
Why this result follows: The intermediate layer does not invent a successful value.
8. Run cleanup after failure
Problem: Trace a local finally marker following an awaited failure.
- The awaited operation fails and the catch prints failed.
- The finally block then prints cleanup before the function exits.
Future<void> work() async => throw StateError('bad');
Future<void> main() async {
try { await work(); } on StateError { print('failed'); }
finally { print('cleanup'); }
}
failed
cleanup
Finally provides a common control-flow path for cleanup. This asynchronous illustration is reasoned and unexecuted.
Why this result follows: Finally provides a common control-flow path for cleanup.
9. Await an asynchronous close
Problem: Wait for a synthetic close before reporting the result.
- The work return is pending while finally awaits close.
- close prints closed before the caller prints done.
Future<void> close() async { print('closed'); }
Future<String> work() async {
try { return 'done'; } finally { await close(); }
}
Future<void> main() async { print(await work()); }
closed
done
The owner’s completion includes its awaited cleanup. This asynchronous illustration is reasoned and unexecuted.
Why this result follows: The owner’s completion includes its awaited cleanup.
10. Prioritize work and cleanup errors
Problem: Choose a caller outcome when work and close both fail.
- The work failure is the specified primary failure in this local policy.
- The cleanup failure is recorded separately and must not silently replace it.
work: StateError
cleanup: close failure
policy: propagate work failure; record cleanup failure safely
A dual-failure policy preserves both important facts. This asynchronous illustration is reasoned and unexecuted.
Expected result: The caller sees the work failure and diagnostics retain the cleanup failure.
Why this result follows: A dual-failure policy preserves both important facts.
11. Ignore a stale result
Problem: Apply only the latest request result after out-of-order completion.
- Request A starts before B, giving B the newer generation token.
- B completes first and updates state; A later fails the token comparison and is ignored.
start A: token 1
start B: token 2
complete B: apply B
complete A: token 1 != current 2; ignore
A generation check protects local state from stale completion. This asynchronous illustration is reasoned and unexecuted.
Expected result: The displayed state remains B.
Why this result follows: A generation check protects local state from stale completion.
12. Ignore completion after disposal
Problem: Prevent a completed request from updating a disposed owner.
- The owner is marked disposed before the pending request completes.
- The completion path checks that flag and skips the state update.
owner: active
start request R
dispose owner
complete R
policy: skip state update
A lifecycle guard protects disposed state without claiming cancellation. This asynchronous illustration is reasoned and unexecuted.
Expected result: No disposed state update occurs under this policy.
Why this result follows: A lifecycle guard protects disposed state without claiming cancellation.
13. Chain a dependent read
Problem: Use a completed ID to start an associated synthetic read.
- The first Future yields A and is awaited.
- The second function receives A and yields item:A.
Future<String> id() async => 'A';
Future<String> item(String id) async => 'item:$id';
Future<void> main() async {
final key = await id();
print(await item(key));
}
item:A
A dependent operation starts after its required value is available. This asynchronous illustration is reasoned and unexecuted.
Why this result follows: A dependent operation starts after its required value is available.
14. Do not assume sibling cancellation
Problem: Assess two started operations when the first awaited Future fails.
- The owner observes the first operation’s failure.
- The second operation has its own lifecycle and is not automatically cancelled by that await.
operation A: started, fails
operation B: started independently
await A: throws
policy: observe or cancel B via its supported API
Each started Future needs its own result and cancellation policy. This asynchronous illustration is reasoned and unexecuted.
Expected result: B is not automatically cancelled by awaiting A.
Why this result follows: Each started Future needs its own result and cancellation policy.
15. Model an ambiguous timeout
Problem: Describe what a caller knows after a write times out.
- The waiting deadline was reached before a definitive local result.
- The remote effect may still have occurred, so the outcome is uncertain.
request: write W
wait: timed out
remote status: not yet known
A timeout is not evidence of remote cancellation or rollback. This asynchronous illustration is reasoned and unexecuted.
Expected result: The write outcome remains uncertain.
Why this result follows: A timeout is not evidence of remote cancellation or rollback.
16. Use a stable request identity
Problem: Plan recovery after a timed-out request with ID R1.
- The same stable ID can identify the original request under a supporting service contract.
- The caller queries or retries according to that contract instead of blindly creating a second effect.
request ID: R1
wait: timed out
recovery: query R1 or retry under documented idempotency contract
Idempotency and outcome queries require actual service support. This asynchronous illustration is reasoned and unexecuted.
Expected result: Recovery keeps the original request identity.
Why this result follows: Idempotency and outcome queries require actual service support.
17. Report a pending state explicitly
Problem: Return a job ID while an owned background process continues.
- The response says pending rather than completed.
- A named owner must observe the eventual result and expose follow-up behavior.
response: pending, job J2
owner: job manager
follow-up: query J2 under documented policy
A pending result is an explicit product contract, not early success. This asynchronous illustration is reasoned and unexecuted.
Expected result: The caller has a pending identifier and follow-up path.
Why this result follows: A pending result is an explicit product contract, not early success.
18. Assign an owner to detached work
Problem: Define a background error path for a deliberately unawaited operation.
- The initiating caller chooses not to wait for completion.
- A background owner still observes errors and defines shutdown behavior.
start operation
owner: background coordinator
error: report through owned handler
shutdown: documented policy
Unawaited work is not automatically safe or durable. This asynchronous illustration is reasoned and unexecuted.
Expected result: The operation has an explicit error and lifetime owner.
Why this result follows: Unawaited work is not automatically safe or durable.
19. Inject a controlled failure
Problem: Test a local owner with a separately completed error.
- The test creates a fresh Completer and starts the owner.
- It completes the Future with StateError and verifies failure rather than success.
fixture: Completer<int>
start: owner(fixture.future)
complete: StateError
assert: failure reported; success absent
A controlled fake isolates the owner’s failure decision. This asynchronous illustration is reasoned and unexecuted.
Expected result: The owner reports the failure path.
Why this result follows: A controlled fake isolates the owner’s failure decision.
20. Combine completion, cleanup and stale checks
Problem: Trace two saves with a latest-request policy and owned cleanup.
- A starts before B; B completes first and updates the current state.
- A completes later but its older token prevents an update; each owner still completes its own cleanup.
start A token=1
start B token=2
complete B: apply B, cleanup B
complete A: ignore stale A, cleanup A
State freshness and operation cleanup are distinct responsibilities. This asynchronous illustration is reasoned and unexecuted.
Expected result: State remains B and both operations own cleanup.
Why this result follows: State freshness and operation cleanup are distinct responsibilities.
Common errors and fixes
Success is reported before work finishes
- Why it happens
- The Future was started without being returned or awaited.
- How to fix it
- Await or return the Future at the owning boundary.
- Prevent it next time
- Use a controlled delayed completion in a test.
A Future failure disappears
- Why it happens
- No caller observes the returned Future or an error is swallowed.
- How to fix it
- Connect the Future to a handler that can recover or propagate.
- Prevent it next time
- Inject a delayed rejection and assert the caller outcome.
A failed request is assumed to undo a server write
- Why it happens
- Client completion and remote effects were treated as one operation.
- How to fix it
- Use the service’s documented status or idempotency contract.
- Prevent it next time
- Test ambiguous outcomes with a controlled service.
20 practice exercises
1. What happens when loadCount throws in the second program?
Show hint
Trace the await before the success print and the catch that follows.
Show worked solution
The awaited Future completes with an error and the catch prints a failure message. The count success line is not reached; returning normally from catch represents handling that error in this demonstration.
The synthetic loadCount Future completes with StateError. Await transfers that failure to the surrounding catch, so the count success print is skipped and the handler prints a failure message. Returning normally from the catch is a recovery decision in this example, not automatic rollback.
Check your solution
- The count success line is not printed.
- The catch receives the failure and prints its message.
2. Does await cancel other work if one Future fails?
Show hint
Identify the particular Future being awaited and the separate work.
Show worked solution
No. Await observes the particular Future’s completion. Other work needs its own cancellation and cleanup policy, and a remote effect may already have happened.
Await observes one Future’s completion; failure does not automatically cancel other independent work. Each started operation needs an owner for result, error and any supported cancellation. A remote effect may already have completed, so follow the actual service’s status or retry contract.
Check your solution
- An unrelated Future is not cancelled merely by the first await failing.
- Cancellation and remote outcome require their own documented mechanisms.
3. A wrapper simply forwards readCount’s Future; another must translate its error. Choose return or await for each.
Show hint
The translating boundary needs to observe completion inside its try.
Show worked solution
The forwarding wrapper can return readCount() directly so its caller owns the same completion. The translating wrapper should await it inside a typed try/catch and return the documented translated outcome. Both designs keep the work connected to an observer.
Check your solution
- The forwarding caller receives the operation Future.
- The translating handler encloses await.
4. Use a fresh Completer to test a save that finishes with value 8 after the owner starts. Specify assertions before and after completion.
Show hint
Attach the owner first and control completion explicitly.
Show worked solution
Create a Completer<int>, start the owner using its Future and verify no success has been reported while pending. Complete it with 8, await the owner and assert the result is 8. Use a new Completer for a separate error test rather than completing one twice.
Check your solution
- No success is reported before completion.
- The completed owner reports 8.
5. Inject a delayed FormatException and a separate StateError using fresh Completers; translate only the first and verify cleanup for both.
Show hint
Attach observers before completing each controlled Future.
Show worked solution
Use separate fixtures: the FormatException follows the documented validation rejection, while StateError propagates as an unexpected failure. Assert neither produces a count success and that each owned cleanup path runs. Do not complete one Completer twice.
Check your solution
- The two error types retain distinct outcomes.
- Both paths check cleanup and absence of success.
6. A UI prints saved immediately after calling save(). Design a controlled test exposing the early-success defect.
Show hint
Keep the save Future pending while observing the UI.
Show worked solution
Inject a fake save backed by a Completer and invoke the UI action without completing it. Assert that saved is absent while pending; the current implementation fails that assertion. Complete the fake, await the fixed owner and then assert saved appears only on success.
Check your solution
- The pending state has no saved message.
- The success message appears after successful completion.
7. A load can fail with FormatException or unexpected StateError. Translate only the former and state the caller outcome for each.
Show hint
Use a typed catch around the await.
Show worked solution
Await inside try and convert FormatException to the documented invalid-input outcome. Allow StateError to propagate to a boundary responsible for unexpected failures, preserving safe context. Neither path should print a count success message.
Check your solution
- FormatException produces invalid input.
- StateError remains an explicit failure.
8. An intermediate handler must log request ID R7 without raw input and rethrow StateError with its stack. Specify both verification checks.
Show hint
Record bounded safe context before rethrow.
Show worked solution
Await in a typed catch, record R7 and a safe category without the payload, then rethrow the active error. Verify the outer caller receives the original StateError and that diagnostics omit sensitive input. Logging and propagation are separate obligations.
Check your solution
- The caller receives the original failure.
- Diagnostics include R7 and omit raw input.
9. A resource close returns Future<void>. Ensure an owner waits for it on success and failure.
Show hint
Await cleanup inside finally.
Show worked solution
Place await resource.close() in finally around the owned work and await the owner in the caller. On both paths cleanup is requested before the owner completes. Verify the real close contract and define how a close error affects a work error.
Check your solution
- Successful work does not complete before required close.
- Failed work still enters the cleanup path.
10. Work fails with E1 and cleanup with E2. Also define the caller result when work succeeds but required cleanup fails.
Show hint
Choose precedence for both the dual-failure and cleanup-only cases.
Show worked solution
When both fail, propagate E1 and record E2 safely as secondary. When work succeeds but required cleanup fails, surface E2 rather than complete success. Test both paths with fresh controlled resources and keep diagnostics bounded.
Check your solution
- The dual failure returns E1 with E2 recorded.
- A cleanup-only failure returns E2.
11. Requests A, B and C start in that order; B completes, then C, then A. Only the newest may update state. Trace every decision.
Show hint
Compare each completion token with current token 3.
Show worked solution
Assign tokens 1, 2 and 3 when starting A, B and C. B is stale when it completes because C already started, C updates state, and A is also stale. Observe all errors and cleanup even for ignored results.
Check your solution
- Only C updates the state.
- A and B remain owned despite their results being ignored.
12. A screen is disposed before a request completes with an error. Define checks for no UI update, error observation and owned cleanup.
Show hint
A lifecycle guard does not cancel or consume an error by itself.
Show worked solution
Mark the screen disposed and skip any later UI update. Still observe and report the Future’s error according to policy and await required cleanup. Test all three obligations with controlled completion; do not claim the underlying request was cancelled.
Check your solution
- No disposed UI state is updated.
- The error and cleanup remain observed.
13. A first Future yields order ID O1; a second depends on it. Design a fake test proving no second call on first failure.
Show hint
Track the second call count under controlled completion.
Show worked solution
Await the first Future before constructing the second request. In the failure fixture assert the second-call count stays zero; in the success fixture complete with O1 and assert that exact ID was passed. Both paths require an error owner.
Check your solution
- First failure leaves the call count zero.
- First success passes O1 to the second request.
14. Tasks A and B start independently; A fails and B later fails too. Define how both errors are observed without assuming cancellation.
Show hint
Each started Future needs an error owner.
Show worked solution
Handle A’s failure and keep an attached observation path for B; record or propagate B’s later failure under the product policy. If cancellation is needed, use B’s supported API and observe cancellation separately. A’s failure does not automatically cancel B.
Check your solution
- Both A and B failures are observed.
- No sibling cancellation is inferred from A’s failure.
15. A write times out locally and the service has no immediate status response. Define user feedback and the information retained for later reconciliation.
Show hint
Represent uncertainty instead of choosing success or failure.
Show worked solution
Report pending or uncertain under the product policy, retain the stable request identity and safe diagnostic context, and avoid issuing a new effect until the service’s recovery protocol permits it. The write may have succeeded, failed or still be running.
Check your solution
- The user is not told the write definitely failed.
- The request identity is retained for reconciliation.
16. A timed-out request K9 has status success, then a different request K10 has unknown status. Decide the next action for each.
Show hint
Use the service’s documented identity and outcome-query contract.
Show worked solution
For K9, report confirmed success without creating a second effect. For K10, retain its identity and report uncertainty or follow the documented idempotent retry protocol; do not treat unknown as definite failure. Record both decisions without exposing sensitive payloads.
Check your solution
- K9 is not duplicated after confirmed success.
- K10 remains uncertain until resolved under the service contract.
17. A service returns pending job J3, then its status becomes failed. Define the follow-up owner and caller-visible transition.
Show hint
Pending and final failure are distinct states.
Show worked solution
The named job owner observes or queries J3 according to the service contract, initially reports pending, then reports the confirmed failure with safe context. Define shutdown and durable storage separately if observation must survive process loss.
Check your solution
- The initial response is pending with J3.
- The later confirmed failure is not reported as success.
18. A detached save fails after its screen is disposed. Assign error observation, safe diagnostics and a durability policy.
Show hint
The screen lifecycle and the background Future have different owners.
Show worked solution
A background coordinator observes the later error and records a safe request ID without updating disposed UI state. Define shutdown behavior and use durable work state if the save must survive process loss. unawaited alone supplies neither error handling nor durability.
Check your solution
- The disposed screen receives no update.
- A background owner observes the error and has a shutdown policy.
19. Create two separate controlled tests for an owner: one successful value and one delayed error. What must each assert?
Show hint
Use a fresh Completer for each path.
Show worked solution
For success, start the owner with a pending Completer, complete it with a value and assert the result and cleanup. For failure, use another Completer, complete it with the expected error and assert the failure outcome, no success and cleanup. Attach error observation promptly.
Check your solution
- The success test verifies result and cleanup.
- The failure test verifies error, no success and cleanup.
20. Design a save owner with a resource, latest-request token and typed failure boundary. State what happens when older A fails after newer B succeeds.
Show hint
Keep result freshness, error observation and cleanup separate.
Show worked solution
Start A with token 1 and B with token 2; apply B only after successful completion. When A later fails, observe and report its error according to policy without overwriting B, and await A’s owned cleanup. B’s cleanup is also independently owned; neither completion implies cancellation of the other.
Check your solution
- B remains the current displayed result.
- A’s failure and both cleanup paths are observed.
Key takeaways
- Await or return work whose completion the caller owns.
- Handle failure and resource cleanup according to an explicit contract.
- Returning or awaiting the connected Future preserves completion ownership.
- An awaited failure does not cancel unrelated work or roll back external effects.
- A generation check prevents stale local updates but does not cancel the source operation.