I've tried but failed in grasping clearly how javascript promises and await work! I somehow managed to cobble together a function that performs what I need in my node.js micro service, but I'm not sure if I'm doing it the right (optimal) way. Also, I achieved what I wanted using promise without await, but also I haven't done any extensive testing of my code to see if it is indeed running exactly the way I think it is. Here is my code that I currently have and works, but I'm not sure if I'm missing using await for proper functioning:
const QryAllBooks = {
type: new GraphQLList(BookType),
args: {},
resolve(){
return new Promise((resolve, reject) => {
let sql = singleLineString`
select distinct t.bookid,t.bookname,t.country
from books_tbl t
where t.ship_status = 'Not Shipped'
`;
pool.query(sql, (err, results) => {
if(err){
reject(err);
}
resolve(results);
const str = JSON.stringify(results);
const json = JSON.parse(str);
const promises = [];
for (let p = 0; p < results.length; p++){
const book_id = json[p].bookid;
const query = `mutation updateShipping
{updateShipping
(id: ${book_id}, input:{
status: "Shipped"
})
{ bookid
bookname }}`
promises.push(apolloFetch({ query }));
}
//I need an await function so that previous apolloFetch
//goes in sequence of bookid, one after the other
Promise.all( promises ).then(( result) => {
errorLogger(27, 'Error', result);
})
.catch(( e ) => {
errorLogger( 29, 'Error', e );
)};
});
});
}
};
module.exports = {
QryAllBooks,
BookType
};