promise.js代码分析

一、promise chain(可以用以下方式,替代使用在扑捉异常错误,多个if else判断)

   PS:function taskA() 里 增加 “throw new Error("throw Error @ Task A")”,则onRejected(error)打印出日志。

Build Status

来源:http://liubin.github.io/promises-book/#chapter2-how-to-write-promise

二、Promise对象实现Ajax操作:

var getJSON = function(url) {
    var promise = new Promise(function(resolve, reject){
var client = new XMLHttpRequest();
client.open("GET", url);
client.onreadystatechange = handler;
client.responseType = "json";
client.setRequestHeader("Accept", "application/json");
client.send();

function handler() {
if (this.readyState!== 4) {
return;
}
if (this.status === 200) {
resolve(this.response);
}
else {
reject(new Error(this.statusText));
}
};
});
return promise;
};
getJSON("/posts.json").then(function(json)
{
console.log('Contents: ' + json);
},
function(error) {
console.error('出错了', error);
}
);

原文地址:https://www.cnblogs.com/babyfacer/p/4721407.html