簡體   English   中英

Rithim 異步 Javascript 練習使用 fetch 和 promises

[英]Rithim Asynchronous Javascript exercises using fetch and promises

我一直堅持這項練習很多年了,我終於認輸並尋求幫助。

對 Star Wars API [ https://swapi.co/]進行 AJAX 調用,並獲取該系列中每部電影的開頭抓取。 完成后,循環遍歷每部電影的行星數組,並進行更多 AJAX 調用以收集按電影組織的每個行星的名稱。 然后,控制台記錄一個對象數組,其中每個對象都包含特定電影的開頭爬行,以及該電影中出現的每個行星的名稱。

我已經閱讀了一些關於異步 js 的文章並觀看了一些視頻,我“認為?”,我有點明白了。 這真的不想工作。

    var promiseList = [];

    var fetchArray = function(arr) {
      promiseArr = arr
        .map(url => fetch(url)
            .then(res => res.json())
            .then(planet => planet.name)
            );     
      Promise.all(promiseArr)
        .then(data => console.log(data));
    }
    // fetchArray doesn't work at all. Curious if it's possible to run this code as it's technicall synchronous (idk).

    for (let number = 1; number < 8; number ++) {
      var t = fetch(`https://swapi.co/api/films/${number}/`)
       .then(res => res.json())
        promiseList.push(t)
    }

    console.log("NAHANH", promiseList)
    // Prints out [[object Promise] { ... }, [object Promise] { ... }, [object Promise] { ... }, [object Promise] { ... }, 
    [object Promise] { ... }, [object Promise] { ... }, [object Promise] { ... }]

    Promise.all(promiseList)
      .then(films => films.map(film => ({
        "title": film.title,
        "planets": film.planets,
        "opening_crawl": film.opening_crawl,
      })))
    // Works up untill this point, this next then doesn't work, my aim is to alter the film.plants property in every 
    array object and actually fetch the planet rather than just the url!
    // An example print out would be...
    // {
    //  opening_crawl: "Luke Skywalker has vanis...",
    //  planets: ["https://swapi.co/api/planets/61/"],
    //   title: "The Force Awakens"
    //  }]
      .then(films => films.map(film => {
          film.planets = film.planets
            .map(url => fetch(url)
              .then(res => res.json())
              .then(planet => planet.name)
              .catch(error => console.log(error.message))
            );     
      }
      .then(data => console.log(data))
    // Which would then finally resolve to (this is what I want but cannot get at the moment!) 
    //  {
    //    opening_crawl: "Luke Skywalker has vanis...",
    //    planets: ["Yavin IV"],
    //    title: "The Force Awakens"
    //  }]

它幾乎可以工作,我可以返回一個對象。 獲取數組根本不起作用。 我試圖檢索行星名稱的第二次更改不起作用。

首先,將函數fetchArray重命名為fetchPlanetNames ,正如它所做的那樣,並添加一些缺失的返回值。 然后你有一個工作函數,它使主代碼塊更簡單(正如你的意圖:-))。

在主代碼塊中, fetchPlanetNames(...)返回的是 Promise,而不是 Array,因此,在films.map()函子中,您需要fetchPlanetNames(film.planets).then(planets => {/* compose the required film object here */}) 這是您嘗試的一種“由內而外”的版本。

 var fetchPlanetNames = function(arr) { return Promise.all(arr.map(url => { // return the Promise returned by Promise.all(...).then(...) // ^^^^^^ return fetch(url) .then(res => res.json()) .then(planet => planet.name); })) .then(data => { console.log(data); return data; // Remember to return `data`, otherwise undefined will be dlivered. // ^^^^^^^^^^^^ }); }; var promiseList = []; for (let number = 1; number < 8; number ++) { promiseList.push(fetch(`https://swapi.co/api/films/${number}/`).then(res => res.json())); } Promise.all(promiseList) .then(films => { return Promise.all(films.map(film => { // Here, a nested Promise chain allows `film` to remain in scope at the point where 'planets' become available. return fetchPlanetNames(film.planets) .then(planets => { return { 'title': film.title, 'planets': planets, 'opening_crawl': film.opening_crawl }; }); })); }) .then(data => console.log(data));

暫無
暫無

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

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