如何在其他函数之前执行 fetch() ?

我目前正在学习 JavaScript,并一直在使用 API(本例中为雅虎财经)。


目标是使用特定股票的财务数据更新价值表 - 但我需要在更新数据之前获取数据。我以为我可以使用所示的等待/异步,但它不起作用。


有什么指点吗?


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;

}


青春有我
浏览 92回答 1
1回答

qq_花开花谢_0

您主要有两个选择:将代码保留为现在的样子,但使用它来等待运行updateStockTabel:request().then(() => updateStockTabel()); 或者将您更改getStockStatistics为异步函数以执行非常相似的操作,但使用 async/await 语法:async function getStockStatistics(){    //Get symbol from input field    inputSymbol = document.getElementById("inputSymbol").value;    console.log(inputSymbol);    await request();    updateStockTabel();}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript