Javascript Rest API for 循环中的 fetch 调用未为元素设置值

Javascript Rest API fetch calls in for loop not setting value to elements

我正在尝试根据术语列表从维基百科获取图像 URLs(如果存在)。 API 调用在我只调用一次时有效,但一旦它进入 for 循环,它就不会将结果设置为 img src=。如果我输入 alert() 并放慢速度,它肯定会得到 URLs。

我做了一个CodePen来演示:https://codepen.io/justiceorjustus/pen/aeOEvW

最终应该是获取到图片URL,然后根据id设置为图片来源

Javascript:

var wikiImageURLs = ["blueweed",
"buttercup_annual",
"horseweed_(marestail)",
"lambsquarters_common",
"ragweed_common",
"spurge_thyme-leaf",
"bedstraw_annual",
"bluebur",
"burdock",
"clover_white_sweet",
"clover_bur",
"cocklebur",
"croton_wooly",
"dogbane_hemp",
"ironweed_tall",
"lettuce_wild",
"mustard_tanzy",
"radish_wild",
"ragwort_tanzy",
"shepherds_purse",
"amaranth_spiny",
"buttercup_tall",
"chickweed_mouseear",
"clover_white",
"Dandelion",
"dock_curly",
"galinsoga_hairy",
"goatsbeard",
"henbit",
"ironweed_western",
"ivy_ground",
"kochia",
"lespedeze",
"oxalis",
"pennycress_field",
"pepperweed_field",
"pigweed_redroot",
"plantain_broadleaf",
"plantain_narrow-leaf",
"purslane_annual",
"sneezeweed_bitter",
"sowthistle_annual",
"sunflower",
"thistle_Russian",
"vetch",
"violet_wild",
"wormwood_biennial",
"yellow_rocket",
"bindweed_field",
"carrot_wild",
"chicory",
"cinquefoil",
"dogfennel",
"fleabane_annual",
"goldenrod",
"horsenettle",
"kudzu",
"marshelder",
"milkweed",
"pepperweed_perennial",
"pokeweed",
"sesbania_hemp",
"sowthistle_perennial",
"spurge_leafy",
"thistle_bull",
"thistle_Canada",
"thistle_musk_(nodding)",
    "yarrow"];

$(function () {
    $(document).ready(function () {

        for (var i = 0; i < wikiImageURLs.length; i++)
        {
             fetch('https://en.wikipedia.org/api/rest_v1/page/summary/' + wikiImageURLs[i])
                 .then(response => {
                    if(response.ok) return response.json();
                    throw new Error(response.statusText);
                 })
                 .then(function handleData(data) {
                     var wikiImageURL = data.thumbnail.source.replace("320px", "262px");
                     //alert(wikiImageURL);
                    document.getElementById(wikiImageURLs[i]).src = wikiImageURL;
                 })
                 .catch(function handleError(error) {

            });
        }
    });
});

HTML:

<div>
            <img id="blueweed" /> blueweed
        </div>
        <div>
            <img id="buttercup_annual" /> buttercup, annual
        </div>
        <div>
            <img id="horseweed_(marestail)" /> horseweed, (marestail)
        </div>
        <div>
            <img id="lambsquarters_common" /> lambsquarters, common
        </div>
        <div>
            <img id="ragweed_common" /> ragweed, common
        </div>
        <div>
            <img id="spurge_thyme-leaf" /> spurge, thyme-leaf
        </div>
        <div>
            <img id="bedstraw_annual" /> bedstraw, annual
        </div>
        <div>
            <img id="bluebur" /> bluebur
        </div>
        <div>
            <img id="burdock" /> burdock
        </div>
        <div>
            <img id="clover_white_sweet" /> clover, white sweet
        </div>
        <div>
            <img id="clover_bur" /> clover, bur
        </div>
        <div>
            <img id="cocklebur" /> cocklebur
        </div>
        <div>
            <img id="croton_wooly" /> croton, wooly
        </div>
        <div>
            <img id="dogbane_hemp" /> dogbane, hemp
        </div>
        <div>
            <img id="ironweed_tall" /> ironweed, tall
        </div>
        <div>
            <img id="lettuce_wild" /> lettuce, wild
        </div>
        <div>
            <img id="mustard_tanzy" /> mustard, tanzy
        </div>
        <div>
            <img id="radish_wild" /> radish, wild
        </div>
        <div>
            <img id="ragwort_tanzy" /> ragwort, tanzy
        </div>
        <div>
            <img id="shepherd&#39;s_purse" /> shepherd&#39;s purse
        </div>
        <div>
            <img id="amaranth_spiny" /> amaranth, spiny
        </div>
        <div>
            <img id="buttercup_tall" /> buttercup, tall
        </div>
        <div>
            <img id="chickweed_mouseear" /> chickweed, mouseear
        </div>
        <div>
            <img id="clover_white" /> clover, white
        </div>
        <div>
            <img id="Dandelion" /> Dandelion
        </div>
        <div>
            <img id="dock_curly" /> dock, curly
        </div>
        <div>
            <img id="galinsoga_hairy" /> galinsoga, hairy
        </div>
        <div>
            <img id="goatsbeard" /> goatsbeard
        </div>
        <div>
            <img id="henbit" /> henbit
        </div>
        <div>
            <img id="ironweed_western" /> ironweed, western
        </div>
        <div>
            <img id="ivy_ground" /> ivy, ground
        </div>
        <div>
            <img id="kochia" /> kochia
        </div>
        <div>
            <img id="lespedeze" /> lespedeze
        </div>
        <div>
            <img id="oxalis" /> oxalis
        </div>
        <div>
            <img id="pennycress_field" /> pennycress, field
        </div>
        <div>
            <img id="pepperweed_field" /> pepperweed, field
        </div>
        <div>
            <img id="pigweed_redroot" /> pigweed, redroot
        </div>
        <div>
            <img id="plantain_broadleaf" /> plantain, broadleaf
        </div>
        <div>
            <img id="plantain_narrow-leaf" /> plantain, narrow-leaf
        </div>
        <div>
            <img id="purslane_annual" /> purslane, annual
        </div>
        <div>
            <img id="sneezeweed_bitter" /> sneezeweed, bitter
        </div>
        <div>
            <img id="sowthistle_annual" /> sowthistle, annual
        </div>
        <div>
            <img id="sunflower" /> sunflower
        </div>
        <div>
            <img id="thistle_Russian" /> thistle, Russian
        </div>
        <div>
            <img id="vetch" /> vetch
        </div>
        <div>
            <img id="violet_wild" /> violet, wild
        </div>
        <div>
            <img id="wormwood_biennial" /> wormwood, biennial
        </div>
        <div>
            <img id="yellow_rocket" /> yellow rocket
        </div>
        <div>
            <img id="bindweed_field" /> bindweed, field
        </div>
        <div>
            <img id="carrot_wild" /> carrot, wild
        </div>
        <div>
            <img id="chicory" /> chicory
        </div>
        <div>
            <img id="cinquefoil" /> cinquefoil
        </div>
        <div>
            <img id="dogfennel" /> dogfennel
        </div>
        <div>
            <img id="fleabane_annual" /> fleabane, annual
        </div>
        <div>
            <img id="goldenrod" /> goldenrod
        </div>
        <div>
            <img id="horsenettle" /> horsenettle
        </div>
        <div>
            <img id="kudzu" /> kudzu
        </div>
        <div>
            <img id="marshelder" /> marshelder
        </div>
        <div>
            <img id="milkweed" /> milkweed
        </div>
        <div>
            <img id="pepperweed_perennial" /> pepperweed, perennial
        </div>
        <div>
            <img id="pokeweed" /> pokeweed
        </div>
        <div>
            <img id="sesbania_hemp" /> sesbania, hemp
        </div>
        <div>
            <img id="sowthistle_perennial" /> sowthistle, perennial
        </div>
        <div>
            <img id="spurge_leafy" /> spurge, leafy
        </div>
        <div>
            <img id="thistle_bull" /> thistle, bull
        </div>
        <div>
            <img id="thistle_Canada" /> thistle, Canada
        </div>
        <div>
            <img id="thistle_musk_(nodding)" /> thistle, musk (nodding)
        </div>
        <div>
            <img id="yarrow" /> yarrow
        </div>

我不太擅长异步请求,所以我认为这个问题可能有些愚蠢。

该路由的响应中没有图像 URL,数组中还有一些模板中不存在的 ID,并且您有不必要的链式承诺。下面的代码有效,但我硬编码了一张随机图像 URL。一旦您找到新的 API 路由 returns 图像 URL,您可以简单地编辑此代码。

var wikiImageURLs = ["blueweed"];

        for (let i = 0; i < wikiImageURLs.length; i++)
        {
             console.log(wikiImageURLs[i])
             fetch('https://en.wikipedia.org/api/rest_v1/page/summary/' + wikiImageURLs[i]).then(response =>          {
                 console.log(response)
                 document.getElementById(wikiImageURLs[i]).src = 'https://i.imgur.com/4rj27vq.jpg?1';
             }).catch(err=>console.log(err));
        }

在这种情况下,我建议使用递归作为重复循环,因为这样,下一个查询只会在前一个查询完成时发生,因此您的浏览器不会挂起。 示例:

    var wikiImageURLs = [
      "blueweed",
      "buttercup_annual",
      "horseweed_(marestail)",
      "lambsquarters",
      "ragweed",
      "spurge_thyme-leaf",
      "bedstraw_annual",
      "bluebur",
      "burdock",
      "clover_white_sweet",
      "clover_bur",
      "cocklebur",
      "croton_wooly",
      "dogbane_hemp",
      "ironweed_tall",
      "lettuce_wild",
      "mustard_tanzy",
      "radish_wild",
      "ragwort_tanzy",
      "shepherds_purse",
      "amaranth_spiny",
      "buttercup_tall",
      "chickweed_mouseear",
      "clover_white",
      "Dandelion",
      "dock_curly",
      "galinsoga_hairy",
      "goatsbeard",
      "henbit",
      "ironweed_western",
      "ivy_ground",
      "kochia",
      "lespedeze",
      "oxalis",
      "pennycress_field",
      "pepperweed_field",
      "pigweed_redroot",
      "plantain_broadleaf",
      "plantain_narrow-leaf",
      "purslane_annual",
      "sneezeweed_bitter",
      "sowthistle_annual",
      "sunflower",
      "thistle_Russian",
      "vetch",
      "violet_wild",
      "wormwood_biennial",
      "yellow_rocket",
      "bindweed_field",
      "carrot_wild",
      "chicory",
      "cinquefoil",
      "dogfennel",
      "fleabane_annual",
      "goldenrod",
      "horsenettle",
      "kudzu",
      "marshelder",
      "milkweed",
      "pepperweed_perennial",
      "pokeweed",
      "sesbania_hemp",
      "sowthistle_perennial",
      "spurge_leafy",
      "thistle_bull",
      "thistle_Canada",
      "thistle_musk_(nodding)",
      "yarrow"
    ];

    function fetchWikipedia(counter) {
      if (counter < wikiImageURLs.length) {
        fetch('https://en.wikipedia.org/api/rest_v1/page/summary/' + wikiImageURLs[counter])
            .then(response => {
                if (response.ok)
                  return response.json();
                  throw new Error(response.statusText);
            })
            .then(function handleData(data) {
                if (data.thumbnail) { //I added this line, cause sometimes the query doesn't come with the thumbnail attribute 
                  var wikiImageURL = data.thumbnail.source.replace("320px", "262px");
                  document.getElementById(wikiImageURLs[counter]).src = wikiImageURL;
                }
                fetchWikipedia(counter + 1);
            })
            .catch(function handleError(error) {
                fetchWikipedia(counter + 1);
            });
       }
    }

    $(function () {
      $(document).ready(function () {
        fetchWikipedia(0);//value initial of counter
      });
    });