Reputation: 2750
I am using a variable like below :
var maxId=1;
schema.table.max('id').then(function(max) {
maxId=max+1;
}).catch(err => {
maxId=1;
});
to take the maximum id from the DB and add one.
console.log(maxId) //prints the maximum id.
I also want to add the new id for the new data by below :
schema.table.findAll({where: option}).then((existed) => {
for (let insert of insertionList) {
insert['id'] = maxId;
maxId=maxId+1;
}
})
Here insertionList's id attribute is showing as NaN instead of the max .
I used let and var but both resulted in NaN. Any help is appreciated.
Upvotes: 0
Views: 504
Reputation: 822
This is a generic answer, not only based on what you wrote. It will help you to debug your problem and write more concise code. Declaring a variable somewhere and change it within a promise is a very bad practice, you can create something unpredictable and it can be based on race conditions. Your variable at the time you read it can be easily undefined or something. It's all based on timing.
Something like:
var maxId=1;
schema.table.max('id').then(function(max) {
maxId=max+1;
}).catch(err => {
maxId=1;
});
can be easily translated to:
const maxId = await schema.table.max('id')
.then(max => {
// here some checks on max (can it be null or undefined?)
return max + 1;
}, () => 1);
To avoid side effects try to use "const" as much as you can instead of "let" and "var". If you are forced to use let or var in most of cases means you are doing it wrong especially when you use promises or async code.
An important consideration....
What you wrote implies that an error would consider max == 1. Throwing an error (or reject a promise) should be handled in a proper way (and not like your example, not even like in mine...). The library you use probably would reject your promise in case of an I/O issue or a lack of permission. Those cases shouldn't imply max = 1 but they should be reported in order to take additional actions.
Upvotes: 2
Reputation: 1186
undefined + 1
=> NaN
I think that when your db is empty, it wont pass by your catch statement because there had been no error trying to get the max value (even if it is undefined
).
You should handle the case of max being undefined.
Here is my solution written in ES6:
let maxId = 1;
schema.table.max('id')
.then(max => maxId = (max || 0) + 1)
Upvotes: 0