I am trying to use a Sequelize promise inside of an existing async/await chain. Sequelize returns everything as a promise. I am new to promises and async/await so I am using this as something of a learning experience. Please be extra patient with me.
My logic looks like this:
if row does not exist from previous '.then'
create a new row and extract the new id
else
extract id value from previous '.then'
So now I have a WORKING block of code now (below), from studying many excellent SO examples. I want to use all anonymous functions since IMHO it makes it a little bit easier to read. (yes debatable point, but for now I want to try getting this working with anonymous functions.
It seems odd to have three nested return statements. Is there a way to rewrite this block of code to be a bit cleaner but just using anonymous functions?
yourTable.findAll( {...})
.then( (data) => {
// more code
})
.then( (data) => {
// more code
})
.then( (data) => {
if ( !Array.isArray(data) || !data.length ) {
// if record does NOT exist
return (async function () {
return await
(function () {
return new Promise( resolve => {
myTable.create( { ........ }
).then( (result) => {
resolve(result._id);
})
})
})();
})()
/* we had to create one, so we return the *NEW* _id value */
} else {
/* we found one, so we just return the pre-existing _id value */
return data[0]._id ;
}
})
.then( (data) => {
// more code
})
.then( (data) => {
Thank you all.