将数据从API推送到数组

时间:2018-09-12 16:51:34

标签: javascript arrays api xmlhttprequest fetch

我无法理解如何将数据从API传递到数组。我想做的是获取一个国家的当前人口,然后将其放入数组。哪个国家/地区取决于输入内容。

我走对了吗?我怎样才能做到这一点?我已经尝试了很多不同的地方,并且这段代码是我得到的最新代码。

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();
    };
  });
}

1 个答案:

答案 0 :(得分:0)

我建议您先阅读该页面,然后再继续进行

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 = "";
    });