我正在玩ajax&迭代承诺为ajax调用创建抽象版本。以下代码工作正常。
function ajax(url){
var xhr = {
rq : function (method, url){
var prom = new Promise(function (resolve, reject){
var client = new XMLHttpRequest();
//only accept
client.open(method,url,true);
client.send();
client.onload = function (){
if(this.status == 200){
if(this.response == "1"){
reject(this.response);
}
else{
resolve(this.response);
}
}
else{
reject(this.statusText);
}
};
});
return prom;
}
};
return {
'get' : function(){
return xhr.rq('GET', url);
}
};
}
但是我想抽象ajax.onload上的函数作为回调传递,我正在考虑这样的事情:
function ajax(url, checker){
var xhr = {
rq : function (method, url){
var prom = new Promise(function (resolve, reject){
var client = new XMLHttpRequest();
//only accept
client.open(method,url,true);
client.send();
client.onload = checker;
};
});
return prom;
}
};
return {
'get' : function(){
return xhr.rq('GET', url);
}
};
}
function chk1(){
if(this.status == 200){
if(this.response == "1"){
reject(this.response);
}
else{
resolve(this.response);
}
}
else{
reject(this.statusText);
}
}
不幸的是,我得到了解决和拒绝未知的错误。我有点知道问题只是在chk1内,这个承诺是未知的。但我不确定如何解决它。
我希望能够这样称呼它:
Promise.all([ajax(u,chk1).get(),ajax(v,chk1).get()])
.then(callback.success)
.catch(callback.error);
亲切的问候
答案 0 :(得分:2)
您可以将resolve
和reject
传递给检查功能,以便根据需要调用它们。
function ajax(url, checker) {
var xhr = {
rq: function(method, url) {
var prom = new Promise(function(resolve, reject) {
var client = new XMLHttpRequest();
//only accept
client.open(method, url, true);
client.send();
client.onload = function() {
checker.call(this, resolve, reject);
};
});
return prom;
}
};
return {
'get': function() {
return xhr.rq('GET', url);
}
};
}
function chk1(resolve, reject) {
if (this.status == 200) {
if (this.response == "1") {
reject(this.response);
} else {
resolve(this.response);
}
} else {
reject(this.statusText);
}
}
答案 1 :(得分:1)
对任何仍在乎的人。 jfriend00的答案是黄金。我的最终解决方案看起来像这样(我不得不改用另一个参数):
function ajax(url, checker){
var xhr = {
rq : function (method, url){
var prom = new Promise(function (resolve, reject){
var client = new XMLHttpRequest();
//only accept
client.open(method,url,true);
client.send();
client.onload = checker(resolve, reject, client);
});
return prom;
}
};
return {
'get' : function(){
return xhr.rq('GET', url);
}
};
}
function chk1(resolve, reject, xhr){
if(xhr.status == 200){
if(xhr.response == "1"){
reject(xhr.response);
}
else{
resolve(xhr.response);
}
}
else{
reject(xhr.statusText);
}
}