Reputation: 163
Try to use Promises in my application on node.js. But faced with a trouble.
Is it possible for catch()
to get applicationObject
(just created in then()
)?
How to pass applicationObject
into catch()
?
Error can be evoked by any cases - either by forcing a throw everywhere in application scoped by execute()
or by system error.
Code example:
new Promise((resolve, reject) => {
// Create applicationObject (used a Singleton pattern)
let applicationObject = Application.getInstance();
resolve(applicationObject);
})
.then(applicationObject => {
// Working with applicationObject
applicationObject.dbModel.beginTransaction();
applicationObject.execute();
applicationObject.dbModel.commit();
})
.catch(error => {
// In any error case try to make some actions with this object
// including rollback db changes
applicationObject.dbModel.rollback(); // How to get applicationObject?
...
}
Upvotes: 0
Views: 69
Reputation: 425
If the error occurs inside the library, there is no way to get applicationObject
in .catch()
. If you want to use applicationObject
in .catch()
, you should keep the object outside of Promise
.
let applicationObject;
new Promise((resolve, reject) => {
applicationObject = Application.getInstance();
resolve(applicationObject);
})
.then(applicationObject => {
applicationObject.dbModel.beginTransaction();
applicationObject.execute();
applicationObject.dbModel.commit();
})
.catch(error => {
if (!applicationObject) {
// In this case, the error occured while creating applicationObject, so you should not call application.dbModel or something.
return;
}
// In this case applicationObject created successfully, and the error occured while executing dbModel issue.
// You should call rollback or something here.
applicationObject.dbModel.rollback();
...
}
Upvotes: 1
Reputation: 82136
Firstly, if it's a Singleton then you could simply just recall Application.getInstance()
inside the catch, if it's implemented correctly then it should have no additional cost.
Alternatively, just create it outside the Promise e.g.
let applicationObject = Application.getInstance();
new Promise((resolve, reject) => {
...
})
.catch(err => {
// applicationObject is accessible
})
Or if it has to be created by the Promise, then just create the var outside the Promise i.e.
let applicationObject = null;
new Promise((resolve, reject) => {
applicationObject = Application.getInstance();
...
})
Upvotes: 1