promise对象调试

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        <script type="text/javascript">
            const p1 = new Promise(function (resolve, reject) {
              setTimeout(() => resolve("test"), 2000)
            })
            
            const p2 = new Promise(function (resolve, reject) {
                //经过调试发现,resolve的内容和状态能被传入的promise实例覆盖,如果是reject则不能被覆盖。
              setTimeout(() => reject(p1), 3000)
            })
            
            console.log(p1);
            console.log(p2);
            p2
              .then(function(result) {
                  console.log(result);
                  return "chenyujie";})
              .catch(function(error ) {
                  console.log("testsss");
                  console.log(error);
                  return p2;})
              .then(function(result) {
                  console.log(result);
                  console.log(this);}, 
                    function(error){
                      console.log("zhongguo");
                      console.log(error);
                    })
              // .catch(result => {
                 //  console.log(result);
              // })
        </script>
    </body>
</html>

then函数返回一个promise对象,promise对象有两个基本属性,状态和结果,其中then回调函数的返回值如果是字符串则直接为结果,状态为fulfilled,如果返回值为promise对象,则以对象状态和结果为准。(具体情况可以调试看,不一定准确,该对象有点麻烦)

 

 

var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;

const getJSON = function(url) {
  const promise = new Promise(function(resolve, reject){
    const handler = function() {
      if (this.readyState !== 4) {
        return;
      }
     // console.log(this);
      if (this.status === 200) {
        console.log(this.responseType)
        resolve(this.responseType);
      } else {
        console.log(this.status)
        console.log("-------------"+this.statusText+"----------------")
        reject(new Error(this.statusText));
      }
    };
    const client = new XMLHttpRequest();
    //client.open("GET", url, false);   //第三个参数设置为false,使得函数执行为同步操作
    client.open("GET", url);
    client.onreadystatechange = handler;
    client.responseType = "html";
    client.setRequestHeader("Accept", "text/html");
    console.log("test1")
   client.send();
    console.log("test2")

  });

  return promise;
};

//getJSON("https://www.baidu.com/wang")

getJSON("https://www.baidu.com/wang").then(function(json) {
  console.log('Contents: ' + json);
}, function(error) {
  console.log('出错了', error);
});

 

posted @ 2021-07-26 21:15  小德cyj  阅读(246)  评论(0编辑  收藏  举报