如何从resolve()和reject()中获取多个值?
我希望 resolve()
返回 {valid_to: cert.valid_to, statusCode, statusMessage}
并且 reject()
应该返回 {错误:-1,状态代码,状态消息}
。
问题
当 statusCode
和 statusMessage
位于不同范围时,我该怎么做?
const https = require('https');
(async () => {
const options = {
hostname: "github.com",
port: 443,
path: '/',
method: 'GET',
timeout: 1000
};
options.agent = new https.Agent(options);
let valid_to = await new Promise((resolve, reject) => {
const req = https.request({
...options, checkServerIdentity: function (host, cert) {
resolve(cert.valid_to);
}
}).on('error', error => {
reject(-2);
});
req.on("timeout", chunk => {
reject(-1);
});
req.on('response', response => {
console.log(response.statusCode);
console.log(response.statusMessage);
});
req.end();
}).catch(error => {
console.log(error);
return -3;
});
})();
I would like both resolve()
to return {valid_to: cert.valid_to, statusCode, statusMessage}
and reject()
should return {error: -1, statusCode, statusMessage}
.
Question
How can I do that, when statusCode
, statusMessage
are in a different scope?
const https = require('https');
(async () => {
const options = {
hostname: "github.com",
port: 443,
path: '/',
method: 'GET',
timeout: 1000
};
options.agent = new https.Agent(options);
let valid_to = await new Promise((resolve, reject) => {
const req = https.request({
...options, checkServerIdentity: function (host, cert) {
resolve(cert.valid_to);
}
}).on('error', error => {
reject(-2);
});
req.on("timeout", chunk => {
reject(-1);
});
req.on('response', response => {
console.log(response.statusCode);
console.log(response.statusMessage);
});
req.end();
}).catch(error => {
console.log(error);
return -3;
});
})();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我会做这样的事情。
编辑:您需要在
https.request
对象中指定res.on('data')
。否则,由于流中没有活动,超时将始终发出。您可以在
res.on("data")
或res.on("end")
中解析,这取决于您的用例。res
是 IncomingMessage 对象由 http.ClientRequest 创建 并分别作为第一个参数传递给“请求”和“响应”事件。req
是 对原始 http.ClientRequest 的引用。两个流都可以发出事件,您可以单独处理它们。
另外,当你拒绝 Promise 时,你实际上无法从
req
中获取 statusCode 和 StatusMessage,因为req
和.on("响应”)
将不会被发出。因此,您需要自己自定义statusCode
和statusMessage
。I will do something like this.
Edit: You need to specify
res.on('data')
in thehttps.request
Object. Otherwise, timeout will always emit because there is no activity from the stream.You can resolve in
res.on("data")
orres.on("end")
and it is up to your use case.res
is an IncomingMessage object is created by http.ClientRequest and passed as the first argument to the 'request' and 'response' event respectively.req
is A reference to the original http.ClientRequest.Both streams can emit events and you may handle them separately.
Also, when you reject the Promise, you actually cannot get the statusCode and StatusMessage from the
req
because there is an error in thereq
and the.on("response")
will not be emitted. So, you need to customize thestatusCode
andstatusMessage
yourself.