Thursday 18 May 2017

nodejs queue of promises or $q or deferred, how can I do this?

I am very new to async programming and have never done a queue of promises before, so I have no idea how to solve this.

I have a table with bank-accounts

for each bank account I have a list of receipts

Account 111
 - Receipt 001
 - Receipt 002
 - Receipt 003

Account 222
 - Receipt 004
 - Receipt 005
 - Receipt 006

So I set up a promise that find() all the bank accounts.

And then I loop thru all bank accounts, and for each account I find all receipts.

What should I do? Create a promise for each receipt find()?

Create an array of promises? (how do you do that btw)

Or is there a third option?

// 
// Find all bank accounts
// 
var findBank = new Promise(
    (resolve, reject) => {
    bankTable.find({}
    ,function(err, data) {
        if (!err) {
            resolve(data);
        } else {
            reject(new Error('findBank ERROR : ' + err));
        }
    });
});


// 
// Find the RECEIPTS for each bank account
// 
var findAllReceipts = function(accountArray) {

    for (var i=0; i<accountArray.length; i++) {

        var findReceipt = new Promise(
            (resolve, reject) => {
            receiptTable.find(
                { accountNo: accountArray[i].accountNo } 
            ,function(err, data) {
                if (!err) {
                    resolve(data);
                } else {
                    reject(new Error('findPrice ERROR : ' + err));
                }
            });
        });
    }
}

// 
// Run the promises
// 
findBank
    .then(findAllReceipts)
    .catch(err => {
        console.log("getbankAccountReport ERR: " + err);
        res.json({error:true,err})
    })



via torbenrudgaard

No comments:

Post a Comment