循环调用多次JSON的函数时出现问题

时间:2019-01-11 18:52:11

标签: javascript asynchronous promise settimeout getjson

我有一个函数(selectWord())收集选定的单词,该函数通过将每个单词循环传递来调用函数(view(单词[i]))。

selectWord():

$('#button').on('click', function() {
  var text = "";
  var lang = $("#lang").text();
  if (window.getSelection) {
    text = window.getSelection().toString();
  } else if (document.selection && document.selection.type != "Control") {
    text = document.selection.createRange().text;
  }
  var word = text.split(" ");
  $('#load').html("");
  var promises = [];

  for (var i = 0; i < word.length; i++) {
    promises.push(Promise.resolve(view(word[i], lang)));
  }

  Promise.all(promises).catch(function(err) {
    console.log("error");
    return err;
  }).then(function() {
    $.each(promises, function(key, val) {
      $.each(val, function(k, v) {
        console.log("promises " + k + " " + v + " " + v[k] + '<br>');
        $('#div').append("promises " + k + " " + v + " " + v[k] + '<br>');
      });
    });
  });
}
});

view():

function view(word, lang) {
  var html = "";
  var id = "";
  img = "";
  ids = [];
  fullLemmas = [];
  gramCats = [];
  setTimeout(wiki(word, lang), 1000);
  setTimeout(function() {
    for (var i = 0; i < ids.length; ++i) {
      if (i == 0) {
        getImg(ids[i], word);
        wiki = fullLemmas[i];
        gramCategory = gramCats[i];
      }
    }
  }, 2000);

  setTimeout(function() {
    for (var i = 0; i < ids.length; ++i) {
      if (i == 0) {
        id = ids[i];
        html += '<li class="col-12 col-md-6 col-lg-3"><div class="cnt-block equal-hight" style="height: 349px;"><figure><img id ="' + id + '" src="' + img + '" class="img-responsive" alt=""></figure><h3><a href="https://es.wikipedia.org/wiki/' + fullLemmas[i] + '">"' + word + ' (' + gramCats[i] + ')' + '"</a></h3>';
      }
      html += '<p><a href="https://es.wikipedia.org/wiki/' + fullLemmas[i] + '">' + fullLemmas[i] + ' (' + gramCats[i] + ')</a></p>';
    }
    html += '</li>';
    return html;
  }, 3000);
}

view函数又调用两个通过getJSON()通过JSON运行的函数,问题是同步。我已经使用了setTimeOut()和Promises,但是我不明白它返回的内容。

显示单词时,它仅保留最后一个单词的数据。

0 个答案:

没有答案