因此,我有两种应该返回承诺的方法。 这些方法就像承诺的XHR,所以我试图将XHR的通用承诺部分提取出来,但是我做不到。
我尝试了几件事。例如:
function sendXHR(reqMethod, reqUrl, successFn, errorFn) {
return new Promise((resolve, reject) => {
let xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = () => {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
try {
resolve(successFn(xmlhttp));
}
catch(ex){
reject(errorFn(ex));
}
}
}
xmlhttp.open(reqMthod, reqUrl, true);
xmlhttp.send();
});
function returnXHRPromise(url) {
return new Promise((resolve, reject) => {
sendXHR('GET', url, function (xmlhttp) { ... some code ...
resolve(...) }, function (ex) { ... some code ...
reject(...) }
})
}
也尝试过
function returnXHRPromise(url) {
sendXHR('GET', url, function (xmlhttp) { ... some code ...
resolve(...) }, function (ex) { ... some code ...
reject(...) }
}
以前是这样-
function returnXHRPromise(url) {
return new Promise((resolve, reject) => {
let xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = () => {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
try {
... some code ... ; resolve(...)
}
catch(ex){
...some code ... ; reject(...);
}
}
}
xmlhttp.open('GET', url, true);
xmlhttp.send();
}
})
}
需要分开约定的XHR部分和该功能的主要工作。