This piece of code showcases the issue:
let someVar: number;
const someFunc = async () => {
someVar = 1;
}
await someFunc();
if (someVar == 1) {
console.log('It is 1');
}
As a result, you will encounter the error:
Variable 'someVar' is used before being assigned
However, it seems perplexing as to why the variable would not be assigned.
I am aware that I could retrieve the value from someFunc
and assign it to someVar
within that function. My query is not about fixing this code but understanding why the error occurs.
(The actual issue stems from the callback function passed to mongoose.connection.transaction
, limiting direct access to its return value - necessitating assignment from within the function).
(TS 4.5.4, node 16.20.0)
PLEASE NOTE: This is NOT a duplicate of Variable 'test' is used before being assigned - Typescript
The solution in that instance pertains to assigning properties of an object before initializing the object itself. This explanation diverges from the current discussion besides the shared error message.
Scenario:
let someVar;
await mongoose.connection.transaction( async (session) => {
//specific mongoose operations occur here.
someVar = await SomeModel.findByIdAndUpdate(id, {newThing});
}
if(someVar)... //error!
While I acknowledge that returning the value and subsequent assignment may resolve the simplified example, the requirement of operating within a callback limits straightforward access to the return value.
Why not simply declare and utilize someVar
within the mongoose transaction to circumvent side effects? The challenge arises when attempting to send it as a response leading to issues like:
Mongoose transaction gives Attempted illegal state transition from [TRANSACTION_COMMITTED] to [TRANSACTION_ABORTED] when Express response sent inside