0

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);
}
  • 2
    `getShares` is never called. However, you have some code in comments. Please provide the code that you actually have a problem with. So if those comments should not be comments, please remove the commenting. – trincot Dec 04 '21 at 15:18
  • Assuming those commented lines should be uncommented to have the problem appear: you should perform the `Promise.all` call *later*, i.e. in the callback that populates that `promises` array, right after the `for (let quote of response)` loop. – trincot Dec 04 '21 at 15:23
  • The problem appears to be that you call `Promise.all(promises)` after the `fetchData(tickerString).then((data) => {});` statement, not right after the loop (which resides in the asynchronous callback). – Bergi Dec 04 '21 at 15:29
  • Ah thank you everyone for the help this worked perfectly. Also, I am pleasantly surprised with how quickly you all were willing to help! I am new to stack overflow but I don't think I can give credit to your answers if it is just a comment right? – Aaron Gettemy Dec 04 '21 at 15:36

0 Answers0