skip to content

A Closure Case

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment) In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

Closures can be used in the scenario of a try-catch block where you want a method to be called inside both of the scopes, depending on the return value of an execution.

In the following snippet, we need to invoke publish() but with a set of common values except for status , which would be the result of the method invoked within the try-catch block.

We can totally go ahead with invoking publish with the values repeated in both the try-catch scopes like below

try {
const result: Result = await anAsyncMethod();
await publish(
IDENTIFIER, {
type: request_type,
requestStatus: REQUEST_STATUS.SUCCESS
}
)
return {
error: null,
value: result.data
}
} catch (err) {
await publish(
IDENTIFIER, {
type: request_type,
requestStatus: REQUEST_STATUS.FAILURE
}
)
throw err;
}

This results in repeated code - which is fine but we can go one step and refactor this with closures.

try {
const result: Result = await anAsyncMethod();
await publishStatus(REQUEST_STATUS.SUCCESS)();
return {
error: null,
value: result.data
}
} catch (err) {
await publishStatus(REQUEST_STATUS.FAILURE)();
throw err;
}

The publishMetric function will be like below

const publishStatus = (status: REQUEST_STATUS) => {
return async () => publish(
IDENTIFIER, {
type: request_type,
requestStatus: status
}
)
}

Closures are quite useful like this and can help us in many scenarios when dealing with asynchronous situations.

Reference


Updated on