简体   繁体   English

将数据从API推送到数组

[英]Pushing data from an API to an Array

I'm having trouble understanding how to pass along data from an API to an array. 我无法理解如何将数据从API传递到数组。 What I'm trying to do is to fetch the current population of a country and then put it in the array. 我想做的是获取一个国家的当前人口,然后将其放入数组。 Which country depends on the input. 哪个国家取决于输入内容。

Am I on the right track? 我在正确的轨道上吗? How can I do this? 我怎样才能做到这一点? I've tried so much different, and this code is the latest I've gotten. 我尝试了很多不同,并且这段代码是我得到的最新代码。

document
  .querySelector("#newListElement")
  .addEventListener("submit", function(e) {
    e.preventDefault();

    getCountry(country).then(function() {
      list.push({
        id: uuidv4(),
        text: e.target.elements.text.value
        /* How do I send along Country Population Today with this object?*/
      });

      saveListElements(list);
      renderList(list);
      e.target.elements.text.value = "";
    });
  });

function getCountry(country) {
  var url = `http://api.population.io/1.0/population/${country}/today-and-tomorrow`;

  return new Promise(function(resolve, reject) {
    var request = new XMLHttpRequest();
    request.open("GET", url, true);
    request.responseType = "json";

    request.onload = function() {
      if (request.status === 200) {
        resolve(request.response);
      } else {
        reject(Error(request.statusText));
      }

      request.onerror = function() {
        reject(Error("Network Error"));
      };

      request.send();
    };
  });
}

I suggest you read that page before going further 我建议您先阅读该页面,然后再继续

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises

//the promise's result is the first argument of the resolve handler.
getCountry(country).then(function(myResult) { 
      list.push({
        id: uuidv4(),
        text: e.target.elements.text.value,
        result:myResult
      });

      saveListElements(list);
      renderList(list);
      e.target.elements.text.value = "";
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM