最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - nodejs array of promises, how can I do this? - Stack Overflow

programmeradmin1浏览0评论

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})
    })

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})
    })
Share Improve this question edited May 18, 2017 at 8:03 Oly 2,4691 gold badge19 silver badges24 bronze badges asked May 18, 2017 at 7:23 torbenrudgaardtorbenrudgaard 2,5619 gold badges35 silver badges59 bronze badges 3
  • If this is in angularjs, take a look at $q.all, which may be what you're looking for. Other promise libraries have similar features as well! – Oly Commented May 18, 2017 at 7:32
  • I did Oly, and $q.all will execute all promises which is in an array $q.all(promisesArray) - but how you I add promises to an array? (in my case findReceipt) – torbenrudgaard Commented May 18, 2017 at 7:36
  • Maximus' answer below is exactly one way to do it - I would suggest the second example using Array.prototype.map is more idiomatic. – Oly Commented May 18, 2017 at 7:58
Add a comment  | 

1 Answer 1

Reset to default 14

Here is how you can do it:

let findAllReceipts = function (accountArray) {
    const a = [];

    for (let i = 0; i < accountArray.length; i++) {
        a.push(new Promise((resolve, reject) => {
            receiptTable.find({accountNo: accountArray[i].accountNo}, function (err, data) {
                if (!err) {
                    resolve(data);
                } else {
                    reject(new Error('findPrice ERROR : ' + err));
                }
            });
        }));
    }

    return Promise.all(a);
};

Or this way using all capabilities of the language:

let findAllReceipts = function (accountArray) {
    return Promise.all(accountArray.map(findReceipts));
};

function findReceipts(account) {
    return new Promise((resolve, reject) => {
        receiptTable.find({accountNo: account.accountNo}, function (err, data) {
            if (!err) {
                resolve(data);
            } else {
                reject(new Error('findPrice ERROR : ' + err));
            }
        });
    });
}
发布评论

评论列表(0)

  1. 暂无评论