以前我有
MyClass.prototype.method1 = function(data1) {
return this.data111.push(data1);
};
MyClass.prototype.method2 = function(i) {
var data = this.method1(i);
if (data.condition1 != null) {
data.onEvent1(this);
}
return $(data.element).someMethod123("data123");
};
MyClass.prototype.method3 = function() {
var data1 = this.method1(this._data1);
return this.someMethod123(step.data1);
};
MyClass.prototype.ended = function() {
return !!this.getState("end");
};
MyClass.prototype.getState = function(key) {
var value = $.cookie(key);
this._options.afterGetState(key, value);
return value;
};
如何使用回调函数进行异步?我想应该是这样的:
MyClass.prototype.method1 = function(data1, callback) {
if(callback){
callback(this.data111.push(data1));
}
else{
return this.data111.push(data1);
}
};
MyClass.prototype.method2 = function(i, callback) {
var data = this.method1(i);
if (data.condition1 != null) {
data.onEvent1(this);
}
if(callback){
callback($(data.element).someMethod123("data123"));
}
else{
return $(data.element).someMethod123("data123");
}
};
MyClass.prototype.method3 = function(callback) {
var data1 = this.method1(this._data1);
if(callback){
callback(this.someMethod123(step.data1));
}
else{
return this.someMethod123(step.data1);
}
};
MyClass.prototype.ended = function(callback) {
if(callback){
callback(!!this.getState("end", /*what should be here and what should it does?*/));
}
};
MyClass.prototype.getState = function(key, callback) {
var oldThis = this;
setTimeout(function(){
value = $.cookie(key);
callback(value, oldThis);
oldThis._options.afterGetState(key, value);
},
0);
};
我肯定错过了一些东西,因为我以前从未在 javascript 中使用过异步函数。就这样吗?
而且,据我所知,要使函数异步,我基本上应该再添加一个参数作为回调函数并摆脱返回,不是吗?