Som*_*ens 167 javascript xmlhttprequest promise
我想在我的前端应用程序中使用(本机)promises来执行XHR请求,但没有庞大框架的所有tomfoolery.
我希望我的XHR返回的希望,但是,这并不工作(给我:Uncaught TypeError: Promise resolver undefined is not a function)
function makeXHRRequest (method, url, done) {
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onload = function() { return new Promise().resolve(); };
xhr.onerror = function() { return new Promise().reject(); };
xhr.send();
}
makeXHRRequest('GET', 'http://example.com')
.then(function (datums) {
console.log(datums);
});
Run Code Online (Sandbox Code Playgroud)
Som*_*ens 337
我假设你知道如何制作原生的XHR请求(你可以在这里和这里刷一下)
由于任何支持本机承诺的浏览器也会支持xhr.onload,我们可以跳过所有的onReadyStateChangetomfoolery.让我们退一步,从使用回调的基本XHR请求函数开始:
function makeRequest (method, url, done) {
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onload = function () {
done(null, xhr.response);
};
xhr.onerror = function () {
done(xhr.response);
};
xhr.send();
}
// And we'd call it as such:
makeRequest('GET', 'http://example.com', function (err, datums) {
if (err) { throw err; }
console.log(datums);
});
Run Code Online (Sandbox Code Playgroud)
欢呼!这不涉及任何非常复杂的事情(如自定义标题或POST数据),但足以让我们前进.
我们可以这样构建一个承诺:
new Promise(function (resolve, reject) {
// Do some Async stuff
// call resolve if it succeeded
// reject if it failed
});
Run Code Online (Sandbox Code Playgroud)
该承诺的构造采用了将传递两个参数的函数(让我们称他们为resolve和reject).您可以将这些视为回调,一个用于成功,一个用于失败.示例很棒,让我们makeRequest用这个构造函数更新:
function makeRequest (method, url) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
resolve(xhr.response);
} else {
reject({
status: this.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = function () {
reject({
status: this.status,
statusText: xhr.statusText
});
};
xhr.send();
});
}
// Example:
makeRequest('GET', 'http://example.com')
.then(function (datums) {
console.log(datums);
})
.catch(function (err) {
console.error('Augh, there was an error!', err.statusText);
});
Run Code Online (Sandbox Code Playgroud)
现在我们可以利用promises的功能,链接多个XHR调用(并且.catch会在任一调用时触发错误):
makeRequest('GET', 'http://example.com')
.then(function (datums) {
return makeRequest('GET', datums.url);
})
.then(function (moreDatums) {
console.log(moreDatums);
})
.catch(function (err) {
console.error('Augh, there was an error!', err.statusText);
});
Run Code Online (Sandbox Code Playgroud)
我们可以进一步改进这一点,添加POST/PUT参数和自定义标题.让我们使用选项对象而不是多个参数,签名:
{
method: String,
url: String,
params: String | Object,
headers: Object
}
Run Code Online (Sandbox Code Playgroud)
makeRequest 现在看起来像这样:
function makeRequest (opts) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open(opts.method, opts.url);
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
resolve(xhr.response);
} else {
reject({
status: this.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = function () {
reject({
status: this.status,
statusText: xhr.statusText
});
};
if (opts.headers) {
Object.keys(opts.headers).forEach(function (key) {
xhr.setRequestHeader(key, opts.headers[key]);
});
}
var params = opts.params;
// We'll need to stringify if we've been given an object
// If we have a string, this is skipped.
if (params && typeof params === 'object') {
params = Object.keys(params).map(function (key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
}).join('&');
}
xhr.send(params);
});
}
// Headers and params are optional
makeRequest({
method: 'GET',
url: 'http://example.com'
})
.then(function (datums) {
return makeRequest({
method: 'POST',
url: datums.url,
params: {
score: 9001
},
headers: {
'X-Subliminal-Message': 'Upvote-this-answer'
}
});
})
.catch(function (err) {
console.error('Augh, there was an error!', err.statusText);
});
Run Code Online (Sandbox Code Playgroud)
在MDN可以找到更全面的方法.
Pel*_*leg 48
这可以像下面的代码一样简单.
请记住,此代码仅在reject调用时触发回调onerror(仅限网络错误),而不是在HTTP状态代码表示错误时触发.这也将排除所有其他例外情况.处理这些应该取决于你,IMO.
另外,建议reject使用实例Error而不是事件本身来调用回调,但为了简单起见,我保持原样.
function request(method, url) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onload = resolve;
xhr.onerror = reject;
xhr.send();
});
}
Run Code Online (Sandbox Code Playgroud)
并调用它可能是这样的:
request('GET', 'http://google.com')
.then(function (e) {
console.log(e.target.response);
}, function (e) {
// handle errors
});
Run Code Online (Sandbox Code Playgroud)
对于现在搜索此内容的任何人,您都可以使用获取功能.它有一些非常好的支持.
我首先使用了@ SomeKittens的答案,但随后发现fetch它对我来说是开箱即用的:)
我认为通过不创建对象,我们可以使最佳答案更加灵活和可重用XMLHttpRequest.这样做的唯一好处是我们不必自己编写2行或3行代码,并且它具有取消对API的许多功能(如设置标题)的巨大缺点.它还从应该处理响应的代码中隐藏原始对象的属性(对于成功和错误).因此,我们可以通过接受XMLHttpRequest对象作为输入并将其作为结果传递来制作更灵活,更广泛适用的函数.
此函数将任意XMLHttpRequest对象转换为promise,默认情况下将非200状态代码视为错误:
function promiseResponse(xhr, failNon2xx = true) {
return new Promise(function (resolve, reject) {
// Note that when we call reject, we pass an object
// with the request as a property. This makes it easy for
// catch blocks to distinguish errors arising here
// from errors arising elsewhere. Suggestions on a
// cleaner way to allow that are welcome.
xhr.onload = function () {
if (failNon2xx && (xhr.status < 200 || xhr.status >= 300)) {
reject({request: xhr});
} else {
resolve(xhr);
}
};
xhr.onerror = function () {
reject({request: xhr});
};
xhr.send();
});
}
Run Code Online (Sandbox Code Playgroud)
此函数非常自然地适用于Promises 链,而不会牺牲XMLHttpRequestAPI 的灵活性:
Promise.resolve()
.then(function() {
// We make this a separate function to avoid
// polluting the calling scope.
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://stackoverflow.com/');
return xhr;
})
.then(promiseResponse)
.then(function(request) {
console.log('Success');
console.log(request.status + ' ' + request.statusText);
});
Run Code Online (Sandbox Code Playgroud)
catch上面省略了以保持示例代码更简单.你应该总是有一个,当然我们可以:
Promise.resolve()
.then(function() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://stackoverflow.com/doesnotexist');
return xhr;
})
.then(promiseResponse)
.catch(function(err) {
console.log('Error');
if (err.hasOwnProperty('request')) {
console.error(err.request.status + ' ' + err.request.statusText);
}
else {
console.error(err);
}
});
Run Code Online (Sandbox Code Playgroud)
禁用HTTP状态代码处理不需要对代码进行太多更改:
Promise.resolve()
.then(function() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://stackoverflow.com/doesnotexist');
return xhr;
})
.then(function(xhr) { return promiseResponse(xhr, false); })
.then(function(request) {
console.log('Done');
console.log(request.status + ' ' + request.statusText);
});
Run Code Online (Sandbox Code Playgroud)
我们的调用代码更长,但从概念上讲,理解正在发生的事情仍然很简单.我们不必为了支持其功能而重建整个Web请求API.
我们可以添加一些便利功能来整理我们的代码:
function makeSimpleGet(url) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
return xhr;
}
function promiseResponseAnyCode(xhr) {
return promiseResponse(xhr, false);
}
Run Code Online (Sandbox Code Playgroud)
然后我们的代码变成:
Promise.resolve(makeSimpleGet('https://stackoverflow.com/doesnotexist'))
.then(promiseResponseAnyCode)
.then(function(request) {
console.log('Done');
console.log(request.status + ' ' + request.statusText);
});
Run Code Online (Sandbox Code Playgroud)
我认为jpmc26的答案非常接近完美。但是,它有一些缺点:
POST-requests设置请求正文。send调用隐藏在函数内部,因此很难阅读。猴子修补xhr对象可解决以下问题:
function promisify(xhr, failNon2xx=true) {
const oldSend = xhr.send;
xhr.send = function() {
const xhrArguments = arguments;
return new Promise(function (resolve, reject) {
// Note that when we call reject, we pass an object
// with the request as a property. This makes it easy for
// catch blocks to distinguish errors arising here
// from errors arising elsewhere. Suggestions on a
// cleaner way to allow that are welcome.
xhr.onload = function () {
if (failNon2xx && (xhr.status < 200 || xhr.status >= 300)) {
reject({request: xhr});
} else {
resolve(xhr);
}
};
xhr.onerror = function () {
reject({request: xhr});
};
oldSend.apply(xhr, xhrArguments);
});
}
}
Run Code Online (Sandbox Code Playgroud)
现在的用法很简单:
let xhr = new XMLHttpRequest()
promisify(xhr);
xhr.open('POST', 'url')
xhr.setRequestHeader('Some-Header', 'Some-Value')
xhr.send(resource).
then(() => alert('All done.'),
() => alert('An error occured.'));
Run Code Online (Sandbox Code Playgroud)
当然,这带来了另一个缺点:猴子修补确实会损害性能。但是,假设用户主要在等待xhr的结果,请求本身花费的时间量比建立呼叫长且xhr请求不经常发送,则这应该不是问题。
PS:当然,如果要针对现代浏览器,请使用fetch!
PPS:在评论中已经指出,此方法更改了可能令人困惑的标准API。为了更好的说明,可以在xhr对象上修补另一种方法sendAndGetPromise()。