如何从resolve()和reject()中获取多个值?

发布于 2025-01-10 07:44:34 字数 1054 浏览 0 评论 0原文

我希望 resolve() 返回 {valid_to: cert.valid_to, statusCode, statusMessage} 并且 reject() 应该返回 {错误:-1,状态代码,状态消息}

问题

statusCodestatusMessage 位于不同范围时,我该怎么做?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

遗失的美好 2025-01-17 07:44:34

我会做这样的事情。

编辑:您需要在 https.request 对象中指定 res.on('data') 。否则,由于流中没有活动,超时将始终发出。

您可以在 res.on("data")res.on("end") 中解析,这取决于您的用例。

resIncomingMessage 对象由 http.ClientRequest 创建 并分别作为第一个参数传递给“请求”和“响应”事件。

req对原始 http.ClientRequest 的引用

两个流都可以发出事件,您可以单独处理它们。

另外,当你拒绝 Promise 时,你实际上无法从 req 中获取 statusCode 和 StatusMessage,因为 req.on("响应”) 将不会被发出。因此,您需要自己自定义 statusCodestatusMessage

const https = require("https");

// {valid_to: cert.valid_to, statusCode, statusMessage}
// {error: -1, statusCode, statusMessage}.

(async () => {
    const options = {
        hostname: "githubasdfa.com",
        port: 443,
        path: "/",
        method: "GET",
        timeout: 1000,
    };

    options.agent = new https.Agent(options);
    try {
        const response = await new Promise((resolve, reject) => {
            let valid_to;
            let statusCode;
            let statusMessage;
            const req = https
                .request(
                    {
                        ...options,
                        checkServerIdentity: function (host, cert) {
                            valid_to = cert.valid_to;
                        },
                    },
                    res => {
                        res.on("data", chunk => {
                            resolve({
                                valid_to,
                                statusCode,
                                statusMessage,
                            });
                        });

                        res.on("end", () => {
                            console.log("No more data in response.");
                        });
                    }
                )
                .on("error", err => {
                    console.log(err);
                    reject({
                        error: -2,
                        statusCode: "custom code",
                        statusMessage: "unhandled error",
                    });
                })
                .on("timeout", chunk => {
                    reject({
                        error: -1,
                        statusCode: "custom code",
                        statusMessage: "unhandled error",
                    });
                })
                .on("response", response => {
                    statusCode = response.statusCode;
                    statusMessage = response.statusMessage;
                })
                .end();
        });

        console.log(response);
    } catch (error) {
        console.log(error);
    }
})();

I will do something like this.

Edit: You need to specify res.on('data') in the https.request Object. Otherwise, timeout will always emit because there is no activity from the stream.

You can resolve in res.on("data") or res.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 the req and the .on("response") will not be emitted. So, you need to customize the statusCode and statusMessage yourself.

const https = require("https");

// {valid_to: cert.valid_to, statusCode, statusMessage}
// {error: -1, statusCode, statusMessage}.

(async () => {
    const options = {
        hostname: "githubasdfa.com",
        port: 443,
        path: "/",
        method: "GET",
        timeout: 1000,
    };

    options.agent = new https.Agent(options);
    try {
        const response = await new Promise((resolve, reject) => {
            let valid_to;
            let statusCode;
            let statusMessage;
            const req = https
                .request(
                    {
                        ...options,
                        checkServerIdentity: function (host, cert) {
                            valid_to = cert.valid_to;
                        },
                    },
                    res => {
                        res.on("data", chunk => {
                            resolve({
                                valid_to,
                                statusCode,
                                statusMessage,
                            });
                        });

                        res.on("end", () => {
                            console.log("No more data in response.");
                        });
                    }
                )
                .on("error", err => {
                    console.log(err);
                    reject({
                        error: -2,
                        statusCode: "custom code",
                        statusMessage: "unhandled error",
                    });
                })
                .on("timeout", chunk => {
                    reject({
                        error: -1,
                        statusCode: "custom code",
                        statusMessage: "unhandled error",
                    });
                })
                .on("response", response => {
                    statusCode = response.statusCode;
                    statusMessage = response.statusMessage;
                })
                .end();
        });

        console.log(response);
    } catch (error) {
        console.log(error);
    }
})();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文