【问题标题】:How to use Promise JS in this case?在这种情况下如何使用 Promise JS?
【发布时间】:2018-03-27 01:32:37
【问题描述】:

我有:

function loadDoc123() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        document.getElementById("demo").innerHTML = this.responseText;
      }
    };
    xhttp.open("GET","demo_get2.asp?fname=Henry&lname=Ford", true);
    xhttp.send();
  }

我想在这段代码中实现 promiseJS 但不编辑代码。我该怎么办?

【问题讨论】:

    标签: javascript node.js promise


    【解决方案1】:

    如果不进行编辑,则无法进行。您需要将代码包装到 Promise 中

    function loadDoc123() {
        return new Promise((res, rej) => {            
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    res(this.responseText);
                }
            };
    
            xhttp.open("GET","demo_get2.asp?fname=Henry&lname=Ford", true);
            xhttp.send(); 
        });
    }
    

    并使用

    loadDoc123().then(text => document.getElementById("demo").innerHTML = text);
    

    【讨论】:

      猜你喜欢
      • 2016-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 2015-11-30
      • 2017-05-16
      • 2012-10-06
      相关资源
      最近更新 更多