I am having issues resolving multiple promises from a for loop. I am fairly new to js, and I know this section of my code is a bit of a mess. I am trying to pull together financial data from multiple sources; yfapi and my database then sanitize it into a format my app will accept.
I need to call a function that returns a promise inside of a for loop. specifically the
for(let quote of response)
loop. I am calling getShares()
which returns a promise and assigning it to promise
. I logged promise inside the for loop and push it to an array of promises
. The log says promise . however, when I log the promises
array outside of the for loop, it is empty. Promise.all(promises) does not resolve since promises is empty.
I believe I am having some sort of async issue. Thanks for the help in advance!
here is the code:
//get all transactions by owner join with traditional
//get all transactions by owner join with crypto
//stringify 10 tickers at a time
//loop through each array of 10
//loop through each ticker
//query yfapi
//update price in the db
//sanitize data
app.get("/aaron", (req, res) => {
let result = {};
// let promises = [];
getTradTransactions("Aaron").then((data) => {
let transactionsFull = data;
getCryptoTransactions('Aaron').then((data)=>{
transactionsFull = transactionsFull.concat(data)
let tickersFull = Array.from(
new Set(transactionsFull.map((transaction) => transaction.ticker))
);
let tickers = splitTickers(tickersFull);
for (let array of tickers) {
let tickerString = array.join(",");
fetchData(tickerString)
.then((data) => {
let response = data.data.quoteResponse.result;
for (let quote of response) {
let { symbol, regularMarketPrice, shortName, quoteType } = quote;
updatePrice(symbol, regularMarketPrice, shortName, quoteType);
//****let promise = (getShares(symbol, quoteType).then((data)=>{****
// let shares = data[0].totalShares
let transactions = transactionsFull.filter(
(el) => el.ticker === symbol
);
for (let i = 0; i < transactions.length; i++) {
transactions[i] = _.omit(transactions[i], [
"date",
"owner",
"created_at",
"updated_at",
"crypto_id",
"traditional_id",
"description",
]);
}
result[symbol] = {
price: regularMarketPrice,
name: shortName,
// shares,
transactions: transactions,
};
// }))
// console.log(promise)
// promises.push(promise)
}
})
// console.log('promises', promises)
// Promise.all(promises)
.then(() => res.status(200).send(result))
.catch((err) => res.status(400).send(err));
}
})
});
});
and getShares():
function getShares(symbol, quoteType) {
let ticker = symbol
let table = "";
quoteType === "CRYPTOCURRENCY" ? (table = "crypto") : (table = "traditional");
return knex(table)
.select('totalShares')
.where({ ticker })
.then((data) => data);
}