簡體   English   中英

如何使用 axios 和 promise 從一組 url 中獲取數據

[英]How to get the data from an array of urls with axios and promises

我有這個端點,它為我提供有關特定字符的信息,如下所示:

端點: https://rickandmortyapi.com/api/character/1 : https://rickandmortyapi.com/api/character/1

這給了我一個帶有字符名稱和其他屬性的對象,其中一個屬性稱為情節。

{
  name: 'Ricky',
  id: 1,
  episode: [...]
}

並且劇集屬性包含一系列如下所示的網址:

[
  "https://rickandmortyapi.com/api/episode/1",
  "https://rickandmortyapi.com/api/episode/2",
  "https://rickandmortyapi.com/api/episode/3"
  ...
]

我知道我應該使用 Promise.all 並以某種方式循環這些然后解決它們,但我無法讓它工作。

這是我試過,但我不知道它是正確的,它總是給回一個承諾,無論多少次,我做的.then

let episodeResponses;

  const episodesResponses = Promise.all(character.episode.map(url => {
    return axios(url)
      .then(resp => episodeResponses = resp)
  }))

  episodesResponses.then(x => console.log(x))

關於如何讓這個工作的任何想法?

謝謝

在簡化的形式中,這個 API 調用看起來像這樣。

const episodes = [
    axios('https://rickandmortyapi.com/api/episode/1'),
    axios('https://rickandmortyapi.com/api/episode/2'),
    axios('https://rickandmortyapi.com/api/episode/3')
];

Promise.all(episodes).then((data) => {
  const episode1 = data[0];
  const episode2 = data[1];
  const episode3 = data[2];
});

改為在Promise.allPromise.all .then() 一旦所有承諾都得到解決,那么您就可以訪問您的數據。

// Create a promise using Promise.all().
const episodeResponses = Promise.all(character.episode.map(url => axios(url)));

// Access the response once all promises are resolved.
episodesResponses.then(x => console.log(x))

暫無
暫無

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

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