0

I am having trouble with a code block which should be running a series of async functions in order. It appears that one await is not properly working. Before this gets closed, I have looked at every related thread I can find on stackOverflow but I cannot seem to resolve this issue or understand why my code is not waiting like it should.

I have a function which will run on a server every minute, so it needs to be async as to not interfere with the rest of the API.

Code follows. If anyone can explain why this error is occurring it will be greatly appreciated.

initial Call

setInterval(() => sn.checkQuoteRequest(), 5000) //10 seconds for testing but will be 1 min in deployment

main function where problem is

exports.checkQuoteRequest = async () =>
{    
    try {
        return new Promise(async function (resolve, reject) {
            let inquries = new Array;
            let quoted = new Array;
            await loadCustomerInq()
                .then(async (response) => {
                    console.log("Load Customer INQ Response:", response);
                    inquries = await response;
                    await filterExpiredInq(inquries)
                        .then(async(response_1) => {
                            quoted = await response_1;
                            console.log("Quoted:", quoted);
                           await fetchCustomerSubscriptions(quoted)//should complete before next function
                                .then(async (response_3) => {
                                    let subscriptions = await response_3;
                                    await sendCustomerOfferNotification(subscriptions) //runs before
                                                                            //prior function finished
                                    .then(async() =>
                                    {   
                                        for(q of quoted) {
                                            await setQuoteNotified(q)
                                                .then(async(response) => {                                                    
                                                     console.log(q, "Notified", await response)
                                                })
                                                .catch((err) => {
                                                    console.log("Set Quoted Notified ERR!", err);
                                                });
                                        };
                                        resolve();
                                    })
                                    .catch((err) => console.log(err));                                                                              
                                });
                        });
                });
        });
    }
    catch (err_1) {
        console.log("Load Customer Inq ERR!", err_1);
    }    
}

function that should be executed before sendOfferNotification


fetchCustomerSubscriptions = (quoted) =>
{        
    let subs = new Array;
    return new Promise(function(resolve, reject) 
    {        
        for(q of quoted)
        {                        
            console.log("Fetch Cus Subs inqID: ", q.inqid)
            pool.query(`SELECT endpoint, expirationTime, p256dh, auth FROM userSubscriptionsView WHERE (inqID = $1 AND notified = $2)`, [q.inqid, false], 
           (err,result) =>
           {
                if(err)
                    console.log(err)
                else
                {
                    console.log("Customer Subscriptions", result.rows)
                    result.rows.forEach((r) =>
                    {
                        console.log("Adding new Customer offer Sub")
                        subs.push(new subscription(r))
                    })
                    console.log("New Subs", subs)
                    
                }

           })
           
        }
        resolve(subs)
    })
}

output

Load Customer INQ Response: [
  { inqid: 20, expiry: 2020-07-01T00:00:00.000Z },
  { inqid: 21, expiry: 2020-07-01T00:00:00.000Z } 
]
Quoted: [
  { inqid: 20, expiry: 2020-07-01T00:00:00.000Z },
  { inqid: 21, expiry: 2020-07-01T00:00:00.000Z } 
]
Fetch Cus Subs inqID:  20
Fetch Cus Subs inqID:  21
0
{ message: 'Notification sent successfully.' }
Set Quote Notified inq { inqid: 20, expiry: 2020-07-01T00:00:00.000Z }
Customer Subscriptions []
New Subs []
{ inqid: 20, expiry: 2020-07-01T00:00:00.000Z } Notified true
Set Quote Notified inq { inqid: 21, expiry: 2020-07-01T00:00:00.000Z }
Customer Subscriptions [
  {
    endpoint: 'https://fcm.googleapis.com/fcm/send/dgYoxNCLMKg:APA91bGyrs5nMIcd3ICta_B_D0tzlkQ34R63TRfHsmBMlUjDCq1wkyprbjNmhUa20MItwQwYIqovZI4xMF0V5VA5Ns0QRqxlRtX_aEhxTo5wfEsuvZoFZaXHihGWaCXFmyCE0qJZnXpT',
    expirationtime: null,
    p256dh: 'BLHt6QPUE2Co3ad9-5wG9f2c46_fph9fxud2zNHRORogttjfg7aS6xMxZYWYQE3DOZAsnJoxivBuhxa7_FrRftc',
    auth: 'Xb9v3Tsuhd2T0RDNXn6LxA'
  },
  {
    endpoint: 'https://fcm.googleapis.com/fcm/send/fhGYWDttRJA:APA91bGeKElvyp2In2ZufGEMLVwM6yz6qPaIBj2h5Hw2tYrRjI2KuPMBYAkSyJTeoRXViHUrvTM_ryUBYqnuCaPTtXk8HeHWBXZHAuic2v-fjrVZT6AOKafwGAutnlHW1C5L2lAuQbyj',
    expirationtime: null,
    p256dh: 'BAfCoSCqSO6-_zDmKXfherzDUhWw_QWHuRtdwU3LK8Yx5LmnndqwuxaTJEI4M14pjx0AX-BmOo2Md0JLevcNG4M',
    auth: '2ZHkYLkvLcVqaK26fU7E7g'
  }
]
Adding new Customer offer Sub
Adding new Customer offer Sub
New Subs [
  subscription {
    endpoint: 'https://fcm.googleapis.com/fcm/send/dgYoxNCLMKg:APA91bGyrs5nMIcd3ICta_B_D0tzlkQ34R63TRfHsmBMlUjDCq1wkyprbjNmhUa20MItwQwYIqovZI4xMF0V5VA5Ns0QRqxlRtX_aEhxTo5wfEsuvZoFZaXHihGWaCXFmyCE0qJZnXpT',
    expirationTime: undefined,
    keys: {
      p256dh: 'BLHt6QPUE2Co3ad9-5wG9f2c46_fph9fxud2zNHRORogttjfg7aS6xMxZYWYQE3DOZAsnJoxivBuhxa7_FrRftc',
      auth: 'Xb9v3Tsuhd2T0RDNXn6LxA'
    }
  },
  subscription {
    endpoint: 'https://fcm.googleapis.com/fcm/send/fhGYWDttRJA:APA91bGeKElvyp2In2ZufGEMLVwM6yz6qPaIBj2h5Hw2tYrRjI2KuPMBYAkSyJTeoRXViHUrvTM_ryUBYqnuCaPTtXk8HeHWBXZHAuic2v-fjrVZT6AOKafwGAutnlHW1C5L2lAuQbyj',
    expirationTime: undefined,
    keys: {
      p256dh: 'BAfCoSCqSO6-_zDmKXfherzDUhWw_QWHuRtdwU3LK8Yx5LmnndqwuxaTJEI4M14pjx0AX-BmOo2Md0JLevcNG4M',
      auth: '2ZHkYLkvLcVqaK26fU7E7g'
    }
  }
]
{ inqid: 21, expiry: 2020-07-01T00:00:00.000Z } Notified true

these two lines should be last

0
{ message: 'Notification sent successfully.' }
d0rf47
  • 409
  • 8
  • 20
  • i feel this should be an async func `fetchCustomerSubscriptions = async (quoted) =>{}` – Karl L Jul 01 '20 at 01:52
  • you mean where the module.export = fetchCustomerSubscriptions? How come? – d0rf47 Jul 01 '20 at 01:52
  • 1
    Would be a lot easier to read all this if you chained the promises by returning each one to the next `then()`. No need for all that deep indenting. Also you don't need an outer `new Promise` when everything inside it is promises. See [What is the explicit promise construction antipattern and how do I avoid it?](https://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it) – charlietfl Jul 01 '20 at 01:56
  • Yeah that is what i normally do But i was reading today that if you need the response its better to use await. I was having trouble finding a definative answer as to whether or not .then will always wait for the response before continuing. I was under the impression it was. But I thought i was wrong... – d0rf47 Jul 01 '20 at 01:58
  • So i tired using just .then chaining and tried using only await and neither work still :\ – d0rf47 Jul 01 '20 at 02:14

1 Answers1

1

The resolve() function is called immediately without waiting for the pool.query() to complete. You need to treat the result of each call to pool.query() as separate promises.

fetchCustomerSubscriptions = (quoted) =>
{        
    const promises = []

    for(q of quoted)
    {                        
        console.log("Fetch Cus Subs inqID: ", q.inqid)
        const promise = new Promise((resolve, reject) => {
            pool.query(`SELECT endpoint, expirationTime, p256dh, auth FROM userSubscriptionsView WHERE (inqID = $1 AND notified = $2)`, [q.inqid, false], 
                       (err,result) =>
                       {
                           if(err)
                               console.log(err)
                           else
                           {
                               const subs = []
                               console.log("Customer Subscriptions", result.rows)
                               result.rows.forEach((r) =>
                                                   {
                                                       console.log("Adding new Customer offer Sub")
                                                       subs.push(new subscription(r))
                                                   })
                               console.log("New Subs", subs)
                               resolve(subs)
                           }
                       })
        })
        promises.push(promise)
    }

    return Promise.all(promises)
        .then(subs_list => {
            return [].concat.apply([], subs_list) // flaten [[sub1, sub2], [sub3]] -> [sub1, sub2, sub3]
        }
}
cuspymd
  • 1,048
  • 9
  • 13
  • true. I knew it had to be something with that function but i wasn't sure how exactly to do this. I will try it right now Thanks so much! – d0rf47 Jul 01 '20 at 03:26