Jonas Skalbo
Jonas Skalbo

Reputation: 45

How do i execute fetch() before other funcitons?

I'm currently learning JavaScript, and has been playing around with API's (Yahoo Finance in this example).

The goal is to update a table of values with a specific stock's financial data - but I need to fetch the data, before it updates the data. Thought I could use await/async as shown, but it doesn't work.

Any pointers?

let stats;
let inputSymbol;

let stockName;
let stockSymbol;
let stockPrevClose;
let stockOpen;
let stockMarketCap;
let stockDayHigh;

function getStockStatistics(){
    //Get symbol from input field
    inputSymbol = document.getElementById("inputSymbol").value;
    console.log(inputSymbol);

    request();

    updateStockTabel();
}

//Fetch data from Yahoo Finance API based on variables
const request = async () => { 
    const response = await fetch(`https://apidojo-yahoo-finance-v1.p.rapidapi.com/stock/v2/get-financials?symbol=${inputSymbol}&region=US`, {
    "method": "GET",
    "headers": {
        "x-rapidapi-key": "---",
        "x-rapidapi-host": "---"
    }
    });
    const data = await response.json();
    stats = data;

    console.log(data);
}

//Update statistics in table based on values from Yahoo Finance JSON object
function updateStockTabel() {

    //Change properties
    stockPrevClose = stats.summaryDetail.previousClose.raw;
    stockOpen = stats.summaryDetail.open.raw;
    stockMarketCap = stats.summaryDetail.marketCap.fmt;
    stockDayHigh = stats.price.regularMarketDayHigh.fmt;
    stockName = stats.price.longName;
    stockSymbol = stats.meta.symbol;

    //Connect document properties with variables
    document.getElementById("stocPrevClose").innerText = stockPrevClose;
    document.getElementById("stockOpen").innerText = stockOpen
    document.getElementById("stockMarketCap").innerText = stockMarketCap;
    document.getElementById("dayHigh").innerText = stockDayHigh;
    document.getElementById("stockName").innerText = stockName;
    document.getElementById("stockSymbolOutput").innerText = stockSymbol;
}

Upvotes: 0

Views: 54

Answers (1)

TKoL
TKoL

Reputation: 13892

You have 2 options mainly: leave your code exactly as it is now, but use this to wait to run updateStockTabel :

request().then(() => updateStockTabel());

OR change your getStockStatistics to an async function to do something pretty similar, but with async/await syntax:

async function getStockStatistics(){
    //Get symbol from input field
    inputSymbol = document.getElementById("inputSymbol").value;
    console.log(inputSymbol);

    await request();

    updateStockTabel();
}

Upvotes: 1

Related Questions