簡體   English   中英

如何將異步 function 返回的 object 分配給變量

[英]How to assign an object returned by an async function to a variable

我有一個 function 從網站上抓取數據。 function 是這樣的:

  const getSharesInfo = async () => {
      try {
        const { data } = await axios.get(url);
        const $ = cheerio.load(data);
        const elmSelector =
          "#ctl00_ContentPlaceHolder1_LiveTrading > table > tbody > tr";
        const keys = [
          "Name",
          "LTP",
          "% Change",
          "Open",
          "High",
          "Low",
          "Qty",
          "Close Price",
        ];
        $(elmSelector).each((parentIdx, parentElm) => {
          let keyIdx = 0;
          const sharesObj = {};
          $(parentElm)
            .children()
            .each((childIdx, childElm) => {
              const tdValue = $(childElm).text();
              if (tdValue) {
                sharesObj[keys[keyIdx]] = tdValue;
                keyIdx++;
              }
            });
          console.log(sharesObj);
          return sharesObj;
        });
      } catch (err) {
        console.error(err);
      }
    };

它從抓取的數據中生成一個 object。 然后當我運行 function 它控制台記錄 shareObj 和 output 是這樣的:

{
  Name: 'USLB',
  LTP: '890.00',
  '% Change': '0.79',
  Open: '890.00',
  High: '888.10',
  Low: '888.10',
  Qty: '24'
}
{
  Name: 'VLBS',
  LTP: '849.00',
  '% Change': '0',
  Open: '850.00',
  High: '833.00',
  Low: '834.00',
  Qty: '285'
}
{
  Name: 'WNLB',
  LTP: '927.30',
  '% Change': '-4.4',
  Open: '965.00',
  High: '927.30',
  Low: '965.00',
  Qty: '270'
}

我想抓住它並將它傳遞給家庭路線。 我有這樣的設置路由器。

app.get("/", async (req, res) => {
  const shares = await getSharesInfo();
  res.render("home", { shares });
});

但是當我控制日志共享時,我什么也得不到。 沒有錯誤沒有數據什么都沒有。 它只是打印一些空白區域。 我該如何解決這個問題??

const sharesObj = {}聲明移到對.each的調用之外(=向上移動 3 行)並移動行return sharesObj; 也離開.each循環(例如:將其向下移動兩行)。

截至目前,您.each中創建常量綁定,然后在.each回調中返回它,而不是在getSharesInfo中。

例子:

  const getSharesInfo = async () => {
  try {
    const { data } = await axios.get(url);
    const $ = cheerio.load(data);
    const elmSelector =
      "#ctl00_ContentPlaceHolder1_LiveTrading > table > tbody > tr";
    const keys = [
      "Name",
      "LTP",
      "% Change",
      "Open",
      "High",
      "Low",
      "Qty",
      "Close Price",
    ];
    const sharesObj = {}; // <-- new position
    $(elmSelector).each((parentIdx, parentElm) => {
      let keyIdx = 0;
      //const sharesObj = {}; <-- old position
      $(parentElm)
        .children()
        .each((childIdx, childElm) => {
          const tdValue = $(childElm).text();
          if (tdValue) {
            sharesObj[keys[keyIdx]] = tdValue;
            keyIdx++;
          }
        });
      console.log(sharesObj);
      //return sharesObj; <-- old position
    });
    return sharesObj; // <-- new position
  } catch (err) {
    console.error(err);
  }
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM