@TOC在这里插入代码片
promise写法
在网上看了很多promise写法,用在应用中单纯的.then是无法满足需求的,其中传递参数是很重要的,参照了一些材料写了一个样例。
父类
//这是父类,messege为传入的参数,定义三个属性,用于与子类的属性对比
function Parents(message){
this._message = message;
this._type = 0;
this._me = "";
}
子类
//子类构造函数
var Child= (function () {
function Child(type, message) {
Parents.call(this, message); //这个位置很重要
this._type = type; //向父类传递数据
this.message = message; //子类自己的属性
}
Child.prototype = new Parents(); //继承父类
Child.prototype.constructor = Child;//构造函数
//定义type函数,传入属性
Child.prototype.type = function(type) {
var self = this;
self._type = type?(type==1?1:0):0;
return self; //返回自己,保证后续函数可以按“.”调用
}
//定义method函数,同上
Child.prototype.method = function(method) {
var self = this;
self._method = method?(method.toUpperCase()=='POST'?'POST':'GET'):'POST';
self.header = self._method == 'POST'?"application/x-www-form-urlencoded":'application/json';
return self;
}
//定义get函数,引用Promise,简单理解,resolve是成功情况,reject是失败情况
Child.prototype.get = function(){
return new Promise((resolve, reject) => {
if (this._type == 0){
resolve(this)
}else{
reject("error")
}
});
}
return Child;
})(); //此处有个小括号
引用方法
下面就是promise写法:promiseX.type(0).method(“a”).get().then(function(res){})
message = '登录态已过期';
var promiseX = new Child(0, message);
promiseX .method("").get().then(function(res){
console.log(res);
},function(err){
console.log(err);
});
相关资料
promise:[http://es6.ruanyifeng.com/#docs/promise]
这篇博客探讨了Promise的使用,指出单纯使用.then()处理异步操作的局限性,并强调了参数传递的重要性。作者提供了一个基于Promise的样例,展示了如何通过链式调用来构造复杂的异步流程。样例中,通过promiseX.type(0).method('a').get().then(function(res){})来执行异步操作。此外,博客还引用了相关的Promise学习资料。
4988

被折叠的 条评论
为什么被折叠?



