Reputation: 1999
I have these express functions:
const token = require("./auth").genToken;
const rp = require("request-promise");
const url = "https://books.zoho.com/api/v3/";
module.exports = {
async listInvoices(req, res) {
let response;
try {
const full_url = url + "invoices";
const auth = await token();
response = await rp({
url: full_url,
method: "GET",
headers: auth,
json: true
});
return res.json(response);
} catch (error) {
return res.status(400).send({ error });
}
},
async listBankTransactions(req, res) {
let response;
try {
const full_url = url + "banktransactions";
const auth = await token();
response = await rp({
url: full_url,
method: "GET",
headers: auth,
qs: req.body,
json: true
});
return res.json(response);
} catch (error) {
return res.status(400).send({ error });
}
},
async matchTransactions(req, res) {
let transactions = await module.exports.listBankTransactions(req, res);
let invoices = await module.exports.listInvoices(req, res);
}
};
They have different routes, and I can call them. However, I want the matchTransactions
function to call listInvoices
and listBankTransactions
and store their responses in variables, so I can manipulate these data and then return the matchTransactions
response.
The way my code is right now, listBankTransactions
returns the response instead of storing in transactions
constant, and then there is an exception on the listInvoices
response, because the response was already returned by listBankTransactions
.
What's the best way to achieve what I'm looking for?
Thanks in advance!
Upvotes: 0
Views: 491
Reputation: 2356
I faced same problem recently and didn't find any solution that you're probably thinking of. ;) The way I handled it was to outsource the repeated code of the functions to external functions that are not middleware and make them return promises/resolved promises. Maybe it will help you. I found the then-catch notation much better for this.
const middlewareA = (req, res, next) => {
ascyncCodeOfMiddlewareA
.then(externalLogicFunction)
.then(...)
.catch(...)
}
const middlewareB = (req, res, next) => {
externalLogicFunction()
.then(...)
.catch(...)
}
const externalLogicFunction = () => {
...
return Promise.resolve(something);
}
Upvotes: 2