我需要在Node.js中实现可取消的客户端HTTP请求,不使用外部库。我会提供一个 Promise
对象 - cancellationPromise
- 当请求被取消时该对象会被拒绝。这就是我知道何时需要调用 request.abort()
的方式。
问题是,我应该仅在 https.request
仍处于挂起状态且 response
对象尚不可用时才调用 request.abort()
吗?
或者,即使我已经得到了 response
对象并正在处理响应数据,我也应该调用它,就像下面的代码一样吗?在这种情况下,这是否会停止任何更多的 response.on('data')
事件?
async simpleHttpRequest(url, oauthToken, cancellationPromise) {
let cancelled = null;
let oncancel = null;
cancellationPromise.catch(error => {
cancelled = error; oncancel && oncancel(error) });
try {
const response = await new Promise((resolve, reject) => {
const request = https.request(
url.toString(),
{
method: 'GET',
headers: { 'Authorization': `Bearer ${oauthToken}` }
},
resolve);
oncancel = error => request.abort();
request.on('error', reject);
request.end();
});
if (cancelled) throw cancelled;
// do I need "oncancel = null" here?
// or should I still allow to call request.abort() while fetching the response's data?
// oncancel = null;
try {
// read the response
const chunks = await new Promise((resolve, reject) => {
response.on('error', reject);
const chunks = [];
response.on('data', data => chunks.push(data));
response.on('end', () => resolve(chunks));
});
if (cancelled) throw cancelled;
const data = JSON.parse(chunks.join(''));
return data;
}
finally {
response.resume();
}
}
finally {
oncancel = null;
}
}
cancellationPromise
被拒绝了,那该怎么办? - avo