簡體   English   中英

如何將 promise object 作為字符串數組返回?

[英]How to return promise object as array of strings?

我有以下代碼

const link =
  "https://www.daft.ie/property-for-rent/ireland?location=dublin&location=dublin-city&sort=publishDateDesc";

async function getLinks(url) {
  return fetch(url)
    .then((res) => res.text())
    .then((html) => {
      const $ = cheerio.load(html);
      const sel = '[data-testid="results"] a[href]';
      var links = [...$(sel)].map((e) => e.attribs.href);
      return Promise.all(links);
    });
}

getLinks(link).then(function(links) {
  console.log(links);
});

這會返回一個像這樣的 object 數組

[
  '/for-rent/apartment-105-cabra-road-phibsborough-dublin-7/4071977',
  '/for-rent/apartment-weavers-hall-leopardstown-dublin-18/4073220',
]

我希望它作為字符串數組返回,這樣我就可以更輕松地執行比較操作,這樣我就可以將數組存儲在一個變量中。

我也想知道如何在這個中使用await

我希望它像這樣工作,但目前失敗了

const a = await getLinks(link1);
const b = await getLinks(link2);

其中ab包含字符串 arrays。

我怎樣才能做到這一點?

除非它在async上下文中,否則不能調用await 這就像調用非 Promise then 您可以將其包裝在匿名異步方法中,例如:

(async () => {
  const a = await getLinks(link1);
  const b = await getLinks(link2);
  // do something
})()

...或使用 Promise.all:

(async () => {
  const [a, b] = await Promise.all([getLinks(link1), getLinks(link2)]);
  // do something
})()

如果 Promise 失敗,也強烈建議和最佳實踐將await用法包裝在try...catch塊中。

您可以通過內置URL api 獲得 URL 的第一部分:

 const link = "https://www.daft.ie/property-for-rent/ireland?location=dublin&location=dublin-city&sort=publishDateDesc"; const url = new URL(link); console.log(url.protocol + "//" + url.host);

然后你可以 append 你得到這個鏈接:

const url = new URL(link);

const a = await getLinks(url.protocol + "//" + url.host + link1);
const b = await getLinks(url.protocol + "//" + url.host + link2);

如果您想在頂層使用await ,並且環境不支持頂層 await ,那么是的,您必須創建一個異步 IIFE:

(async () => {
    // your code
})();

暫無
暫無

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

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