console.log("Hello World!");
var $ = require('./dio.js');
var Promise = require('./tria.js');
console.log($,Promise)
var async = function(flag){
var count = Math.round(Math.random()*8+1);//1-9
return new Promise(function(resolve,reject){
//模拟异步成功或失败
if(count%2 == 0){
resolve("成功:"+flag+":"+count);
}else{
reject("失败:"+flag+":"+count)
}
});
}
async("#1").then(function(value){
console.log("then1:",value);
return async("#2");
}).catch(function(value){
console.log("catch1:",value)
}).then(function (value) {
console.log("then2:",value)
},function(value){
console.log("catch2:",value)
})
//https://www.zzzpfm.com/jtvzzjms/wx/choose.do?urlType=restaurant_queryMenuByDate&method=showWeekMenu&time=2018-02-01
/**
* ajax实现(暂未考虑兼容)
* param:{
url:"",
type:"post",
data:{
"id":1
},
async:true,
success:function(data){
},
error:function(status,xhr){
},
change:function(state,event){
}
}
*/
function ajax(param,success,error,change){
success = success || param['success'];
error = error || param['error'];
change = change || param['change'];
//请求的5个阶段,对应readyState的值
//0: 未初始化,send方法未调用;
//1: 正在发送请求,send方法已调用;
//2: 请求发送完毕,send方法执行完毕;
//3: 正在解析响应内容;
//4: 响应内容解析完毕;
var xhr = new XMLHttpRequest(); //创建一个ajax对象
xhr.onreadystatechange = function(event){ //对ajax对象进行监听
var next = change&&change(xhr.readyState,event);
if(!next) return;
if(xhr.readyState == 4){ //4表示解析完毕
if(xhr.status == 200){ //200为正常返回
success&&success(xhr.responseText);
}else{
error&&error(xhr.status,xhr);
}
}
};
xhr.open(param['type']||'get',param['url'],param['async']||true); //建立连接,参数一:发送方式,二:请求地址,三:是否异步,true为异步
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded'); //可有可无
xhr.send(param['data']||null); //发送
}
module.exports = ajax;
function Promise(fn){
var promise = this;
this.resolves = [];
this.rejects = [];
this.value = null;
this.status = 'pending';
this.then = function (fnDone,fnCatch) {
promise.resolves.push(fnDone);
if(fnCatch){
promise.rejects.push(fnCatch);
}
return this;
}
this.catch = function(fnCatch){
if(fnCatch){
promise.rejects.push(fnCatch);
}
return this;
}
function resolve(value){
promise.status = 'fulfilled';
promise.resolves.forEach(function(resolver){
value = resolver(value);
});
}
function reject(value){
promise.status = 'rejected';
promise.rejects.forEach(function(rejecter){
value = rejecter(value);
})
}
function progress(progress){
console.log(progress);
}
setTimeout(function() {
fn&&fn(resolve, reject,progress);
},300);
}
module.exports = Promise;