knex newbie here,trying to move away from sequelize.
i am trying use a series of knex raw calls in a promise.
after much research, i came up with a simple working example, but i would like somebody with a better background in knex/promises to make any suggestions before proceeding.
const firstPromise = ( promiseInput ) => {
return new Promise((resolve, reject) => {
console.log('parameter passed into promise: ' + promiseInput);
knex.raw("SELECT VERSION()")
.then(
(version) => { console.log ('inside: ' + version[0][0]["VERSION()"] );
resolve ('outside: ' + version[0][0]["VERSION()"] );
}
).catch(
(err) => { reject(err); }
)
})
}
const secondPromise = ( input ) => {
return new Promise ( (resolve, reject) => {
resolve (input) ;
})
}
console.log('Starting run.');
firstPromise('promise input.')
.then( (response) => { console.log ('response from firstPromise: ' + response) ;
return response ;
} )
.then( (newResponse) => console.log ('ending! ' + newResponse) )
.then( () => knex.destroy() )
.then( () => secondPromise('stuff into second promise')
.then((result) => { console.log('calling second promise: ' + result); return (result);} ) )
.then( (lastResponse) => console.log ('last response: ' + lastResponse) )
.catch( (error) => console.log ('error! ' + error) )
;
also, please let me know if this is the correct forum for such a question.
thank you for your time and consideration.
side-note: its amazing how much easier knex is over sequelize.
You dont need to create a new promise each time, that's overkill and kinda useless. you can do:
function firstPromise(promiseInput){
console.log('parameter passed into first promise: ' + promiseInput);
return knex.raw("SELECT VERSION()");
}
function secondPromise(promiseInput){
console.log('result of first promise passed into second promise: ' + promiseInput);
return [your knex stuff here]
}
[... other promieses]
firstPromise()
.then(secondPromise)
.then(thirdPromise)
.then(console.log)
Your promises are all taking the result of the previous promise and returning to the next.
Also you don't need to call knex.destroy() because you will close the connection.
p.s. yes you can ask such questions here.