Promise让代码一目了然

ES6的 Promise 解决了js回调地域的问题,原理就不细说了,直接说用法

1.封装一个Ajax 操作的例子

const getJSON = function(url) {
  const promise = new Promise(function(resolve, reject){
    const handler = function() {
      if (this.readyState !== 4) {
        return;
      }
      if (this.status === 200) {
        resolve(this.response);
      } else {
        reject(new Error(this.statusText));
      }
    };
    const client = new XMLHttpRequest();
    client.open("GET", url);
    client.onreadystatechange = handler;
    client.responseType = "json";
    client.setRequestHeader("Accept", "application/json");
    client.send();

  });

  return promise;
};

调用

getJSON("/posts.json").then(function(json) {
  console.log('Contents: ' + json);
}, function(error) {
  console.error('出错了', error);
});

如果是多个有循序的接口调用呢?

1. 嵌套调用

getJSON("/first.json").then(function (first) {
  console.log('Contents: ' + first);
  getJSON("/second.json").then(function (second) {
    console.log('Contents: ' + second);
    getJSON("/third.json").then(function (third) {
      console.log('Contents: ' + third);
    })
  })
}, function (error) {
  console.error('出错了', error);
});

2.链式调用 (既在Promise 里再返回一个Promise)

getJSON("/first.json").then(function (first) {
  console.log('Contents: ' + first);
  return new Promise((resolve => resolve(first)))
}).then((first)=>{
  getJSON("/second.json").then(function (second) {
    console.log('Contents: ' + second);
    return new Promise((resolve => resolve(second)))
  })
}).then((second)=>{
  getJSON("/third.json").then(function (third) {
    console.log('Contents: ' + third);
  })
})

链式调用的优点在于只有先后关系一目了然,一眼能看到逻辑

你可能感兴趣的:(javascript,前端,javascript,js,ajax)