带有异步函数的javascript for循环

时间:2016-07-14 03:41:19

标签: javascript ajax asynchronous promise ecmascript-next

在最后一行,getElementsByClassName找不到元素,因为loadhtml函数是一个AJAX调用。

如何使用异步函数或ES6生成器或承诺,以使最后一行的getElementsByClassName有效?

    TotalArticleNumber = 3;

    for (let i = TotalArticleNumber; i > 0; i--) {
      loadhtml('./article/test' + i + '.md', function(e) {
        sdf(i, e);
      });
    };


    function loadhtml(url,callback) {
     var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
       if (xhttp.readyState == 4) {
        if( xhttp.status == 200){
         var response = xhttp.responseText;
         (callback)(response);
        }
       };
     };

      xhttp.open("GET", url, true);
      xhttp.send();
    };



    function sdf(i, e) {
      var node = document.createElement("DIV");
      var node1 = document.createElement("A");
      var node2 = document.createElement("H1");
      var node3 = document.createElement("P");

      node.setAttribute('class', 'articleInner');
      node1.setAttribute('class', 'openArticle');
      node2.setAttribute('class', 'title');
      node2.setAttribute('id', i);
      node2.innerHTML = e.match(re);
      node3.innerHTML = converter.makeHtml(e.replace(re1, ""));
      node1.appendChild(node2);
      node1.appendChild(node3);
      node.appendChild(node1);

      document.getElementById('articleContent').appendChild(node);
    }

    Array.prototype.forEach.call(document.getElementsByClassName('title'), function(item) {
      item.addEventListener('click', function() {
        document.getElementById('realArticle').style.display = 'block';
        document.body.style.background = 'gray';
      })
    })

1 个答案:

答案 0 :(得分:0)

如果您想使用async功能,则需要将其核心包含在async function块中,并对您使用的每个承诺使用await关键字:

假设loadHtml是异步函数,您可以使用:

function loadHTML(url) {
    return new Promise((resolve, reject) => {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (xhttp.readyState == 4) {
                var response = xhttp.responseText;
                if (xhttp.status == 200) {
                    resolve(response);
                } else {
                    reject(response)
                }
            };
        };
        xhttp.open("GET", url, true);
        xhttp.send();
    })
};
async function loadHtmlAndMakeElements(){
    TotalArticleNumber = 3;
    let promises = []
    for (let i = TotalArticleNumber; i > 0; i--) {
        promises.push(new Promise((resolve, reject) => {
            loadHTML(`./article/test${i}.md`).then(e => {
                sdf(i, e);
                resolve()
            });
        }))
    }
    await Promise.all(promises);
    Array.prototype.forEach.call(document.getElementsByClassName('title'), function(item) {
        item.addEventListener('click', function() {
            document.getElementById('realArticle').style.display = 'block';
            document.body.style.background = 'gray';
        })
    })
}
function sdf(i, e) {
    var node = document.createElement("DIV");
    var node1 = document.createElement("A");
    var node2 = document.createElement("H1");
    var node3 = document.createElement("P");
    node.setAttribute('class', 'articleInner');
    node1.setAttribute('class', 'openArticle');
    node2.setAttribute('class', 'title');
    node2.setAttribute('id', i);
    node2.innerHTML = e.match(re);
    node3.innerHTML = converter.makeHtml(e.replace(re1, ""));
    node1.appendChild(node2);
    node1.appendChild(node3);
    node.appendChild(node1);
    document.getElementById('articleContent').appendChild(node);
}
loadHtmlAndMakeElements()