Reputation: 4488
I'm trying to save a brand new object into my database but only if it doesn't exists yet. For this, I created this method in other to make two validations: (1) if object is missing and (2) if object already exists. If everything is ok, then save. Code is below:
exports.new = (obj) => {
return Promise.resolve(() => {
if (!obj) throw Error('object is missing');
this.getOneAsync(obj).then(repeatedObj => {
if (repeatedObj.length != 0) throw Error('Object already saved!');
return obj;
});
}).then(obj => {
var newObj = createModel(obj);
return newObj.saveAsync();
})
};
Unfortunately, Promise.resolve()
aren't being executed. My code jump straight to then()
clause and obj
isn't what I expected, always returning { length: 0, name: '' }
.
What am I doing wrong? Any help will be appreciated.
Upvotes: 0
Views: 99
Reputation: 4488
After clarifications here, this way works using Promise.resolve()
:
exports.new = (obj) => {
return Promise.resolve().then(() => {
if (!obj) throw Error('object is missing');
this.getOneAsync(obj).then(repeatedObj => {
if (repeatedObj.length != 0) throw Error('Object already saved!');
return obj;
});
}).then(obj => {
var newObj = createModel(obj);
return newObj.saveAsync();
})
};
Upvotes: 0
Reputation: 816422
Promise.resolve()
is executed, but not the function you pass to it. Promise.resolve
immediately resolves the promise with the value you pass to it. It does not call the function. .then
is called with the function you pass to Promise.resolve
.
Promise.resolve
is not useful in your case. Instead do something like
exports.new = (obj) => {
if (!obj) return Promise.reject(new Error('object is missing'));
return this.getOneAsync(obj)
.then(repeatedObj => {
if (repeatedObj.length != 0) throw Error('Object already saved!');
var newObj = createModel(obj);
return newObj.saveAsync();
});
};
Upvotes: 3