• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Babyfacer摩羯座
https://github.com/babyfacer0104
博客园    首页    新随笔    联系   管理    订阅  订阅
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);
}
);

posted on 2015-08-11 16:31  Babyfacer摩羯座  阅读(216)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3