承诺在promise结构中捕获结果

时间:2017-05-18 13:34:11

标签: javascript node.js promise angular-promise

这是我的整个代码,我想要避免的是所有moveAllBank,moveAllReceipt moveAllExpense函数,如果可能的话。下面的代码工作正常,我只是希望有一个更聪明的方法。很难理解不同的承诺如何在彼此之间传递数据。

// 
// Find all bank accounts
// 
var bankModel = require('../models/bankModel');
var bankTable = mongoose.model('bankModel');
var bankArray = [];
var findAllBank = new Promise(
    (resolve, reject) => {
    bankTable.find({}
    ,function(err, data) {
        if (!err) {
            resolve(data);
        } else {
            reject(new Error('findBank ERROR : ' + err));
        }
    });
});
let moveAllBank = function (data) {
    bankArray = data;
    console.log("receiptArray Result: " + JSON.stringify(data, null, 4));
};


// 
// Find the RECEIPT for each bank account
// 
var receiptModel = require('../models/receiptModel');
var receiptTable = mongoose.model('receiptModel');
var receiptArray = [];
let findAllReceipts = function (accountArray) {
    return Promise.all(bankArray.map(findReceipts));
};
function findReceipts(account) {
    return new Promise((resolve, reject) => {
        receiptTable.find({account: account._id}, function (err, data) {
            if (!err) {
                console.log("findReceipts Result: " + JSON.stringify(data, null, 4));
                resolve(data);
            } else {
                reject(new Error('findReceipts ERROR : ' + err));
            }
        });
    });
}
let moveAllReceipt = function (data) {
    receiptArray = data;
    console.log("receiptArray Result: " + JSON.stringify(data, null, 4));
};


// 
// Find the EXPENSE for each bank account
// 
var expenseModel = require('../models/expenseModel');
var expenseTable = mongoose.model('expenseModel');
var expenseArray = [];
let findAllExpense = function (accountArray) {
    console.log("=====EXPENSE====")
    console.log("accountArray Result: " + JSON.stringify(accountArray, null, 4));
    return Promise.all(bankArray.map(findExpense));
};
function findExpense(account) {
    return new Promise((resolve, reject) => {
        expenseTable.find({account: account._id}, function (err, data) {
            if (!err) {
                console.log("findExpense Result: " + JSON.stringify(data, null, 4));
                resolve(data);
            } else {
                reject(new Error('findExpense ERROR : ' + err));
            }
        });
    });
}
let moveAllExpense = function (data) {
    expenseArray = data;
    console.log("expenseArray Result: " + JSON.stringify(data, null, 4));
};


// 
// Send the result
// 
let sendResult = function (data) {
    res.json({error:false,  "bank":bankArray, "receipt":receiptArray, "expense":expenseArray})
};  


// 
// Run the promises
// 
findAllBank
    .then(moveAllBank)
    .then(findAllReceipt)
    .then(moveAllReceipt)
    .then(findAllExpense)
    .then(moveAllExpense)
    .then(sendResult)
    .catch(err => {
        console.error(err);
        console.log("getbankAccountReport ERR: " + err);
        res.json({error:true,err})
    });

1 个答案:

答案 0 :(得分:0)

你想要

findBank
  .then(bank => findAllReceipts(bank)
    .then(receipt => bank.findAllExpense(bank)
      .then(expense =>
        res.json({error:false, bank, receipt, expense})
      )
    )
  )
  .catch(err => res.json({error:true,err});

或者只是

try {
  const bank = await findBank;
  const receipt = await findAllReceipts(bank);
  const expense = await findAllExpense(bank);
  res.json({error: false, bank, receipt, expense});
} catch(error) {
  res.json({error});
}

要使用await,功能必须标记为async