skip to Main Content

I am testing this on playcode.io so it should work for everyone.
In this code


let stockPriceData= new Map();
const generateMapofStockPriceData = async () =>{
    await fetch('https://64607244fe8d6fb29e30eaaf.mockapi.io/Xerodha/V1/StockPriceData')
    .then(response => response.json())
    .then(data => data.forEach(element =>{
      console.log(element.StockPrice);
      stockPriceData.set(element.StockName,element.StockPrice);
    }))
    .catch(error => console.log(error));    
    }
    generateMapofStockPriceData();
    console.log(stockPriceData);
    console.log(stockPriceData.get("ASIANPAINT"));

The first console.log prints the map which makes me believe that the map was already generated but then the next line gives undefined and after the the elements print the stock price which means that the first console log was actually having no data i.e. the stockPriceData map has no data but something like the promise got resolved and I got the data much later. How does this actually work and how do I get the values given the key ?

Note: I put the async await much later without having much idea but it works the same without it.

3

Answers


  1. generateMapofStockPriceData is an asyncronous fn. so all the code below invoking of this func will be executed before finishing it so you have two option

    1. move all code to above fn

    2. pass a callback fn

      let stockPriceData = new Map();        
      const generateMapofStockPriceData = async (callbackFn) => {
      
           const res = await fetch('https://64607244fe8d6fb29e30eaaf.mockapi.io/Xerodha/V1/StockPriceData')
           const data = await res.json()
           data.forEach(element => {
               console.log(element.StockPrice);
               stockPriceData.set(element.StockName, element.StockPrice);
           })
      
           console.log(stockPriceData);
           console.log(stockPriceData.get("ASIANPAINT")); // or you can use call back 
      
           if (callbackFn) callbackFn()
      
       }
      
       generateMapofStockPriceData(); // this will take time code after this will be executed before finishing this . so pass a callback fn to execute after finishing above fn or move required code to above fn 
      
    Login or Signup to reply.
  2. What you’re observing is the asynchronous behavior of the fetch API. When you call generateMapofStockPriceData(), it starts a network request to fetch data from the specified URL and immediately moves on to the next line, which logs the current state of stockPriceData. At this point, stockPriceData is an empty map because the data from the network request has not yet been received.

    Meanwhile, the network request is happening in the background and when it finishes, it invokes the then() method of the Promise returned by fetch. The then() method is passed a callback function that takes the response data and processes it. In your code, this function loops over each element in the response data and adds it to the stockPriceData map using the set() method.

    Since the fetch request is asynchronous, the console.log(stockPriceData) statement is executed before the then() callback that populates stockPriceData with data is invoked. That’s why it logs an empty map.

    To get the values of the map given a key, you can call the get() method on the stockPriceData map, passing in the key as an argument. For example, to get the stock price for "ASIANPAINT", you can use stockPriceData.get("ASIANPAINT"). However, you need to ensure that the get() method is called only after the then() callback that populates the map has been invoked. One way to do this is to chain a second then() method to the fetch call that logs the map with data and also calls get() to retrieve the stock price for "ASIANPAINT". Here’s an example:

    let stockPriceData= new Map();
    const generateMapofStockPriceData = async () =>{
        await fetch('https://64607244fe8d6fb29e30eaaf.mockapi.io/Xerodha/V1/StockPriceData')
        .then(response => response.json())
        .then(data => data.forEach(element =>{
          console.log(element.StockPrice);
          stockPriceData.set(element.StockName,element.StockPrice);
        }))
        .catch(error => console.log(error));    
    }
    
    generateMapofStockPriceData()
    .then(() => {
      console.log(stockPriceData);
      console.log(stockPriceData.get("ASIANPAINT"));
    })
    .catch(error => console.log(error));
    

    In this code, we chain a second then() method to generateMapofStockPriceData(). This then() method logs the map with data and also calls get() to retrieve the stock price for "ASIANPAINT". The catch() method catches any errors that occur during the fetch request or processing of the response data.

    Login or Signup to reply.
  3. async function fetchingRequest() {
        const response = await fetch('https://some_url_to_fetch_data_from');
        const json = await response.json();
        console.log(json);
    }
    
    fetchingRequest()
    

    await substitutes for .then(), so when using await fetch, you don’t need to use .then() at all.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search