无法存储从回调函数返回的值

时间:2018-08-20 10:37:02

标签: javascript json ajax

我有一个名为 fnswiftWordApi 的函数,该函数向API发送异步请求并返回值。但是我无法存储从API返回的值。我在给定的参数中使用了回调函数下面的代码。我需要将返回的值存储在一个名为word_item的变量中。

let fnsiwftWordApi = (function() {
  let word_item = [];
  let uniq_Id = Math.floor(Math.random() * (8 - 1 + 1) + 1);
  let wordapi = new fnwordApi();

  let callbackwithdata = function(err, res) {
    let splitted;
    //Store split items in
    word_item.push(res.body.split(" "));
  };

  console.log(word_item);
  wordapi.getword(
    `https://jsonplaceholder.typicode.com/posts/${uniq_Id}`,
    callbackwithdata
  );
  return word_item;
})();

wordapi.js

  let fnwordApi = (function() {
  let fnwordApi = function() {
    this.http = new XMLHttpRequest();
  };

  fnwordApi.prototype.getword = function(url, callback) {
    let self = this;
    this.http.open("GET", url, true);
    this.http.onload = function() {
      callback(null, JSON.parse(self.http.responseText));
    };
    this.http.send();
  };

  return fnwordApi;
})();

0 个答案:

没有答案