Remembering a Successful Call Even When It Returns Zero

The audit wrapper added a line to every quote and still handed back the same price. The desk’s setup step needs a different kind of wrapper. The Python script prepares the desk exactly once, however many times it’s asked, and its final report says Setups: 1. The setup’s answer is 0, and that zero counts as a successful result like any other.

In this lesson, you’ll port that run-once behavior to JavaScript, starting from its contract, which says what the wrapper must remember and when that may change.

State the Contract Before the Code

A once wrapper promises four things. The first successful call runs the wrapped function and saves what it returned. Every later call returns that saved result without running the function again. An object result isn’t copied, so every caller gets the same object. If a call throws instead of returning, nothing is saved, so the next call tries again.

That contract needs two pieces of state. One holds the result. The other records whether a call has succeeded. You can’t merge them, because the result can be any value. The desk’s setup returns 0, and a setup with no return gives back undefined, so a test on the value alone can’t tell “already ran” from “never ran”.

The Python script keeps both in a closure. nonlocal lets the inner function reassign the names it shares with once(), and called is a Boolean of its own, separate from result:

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.