有人可以解釋為什么我的catch()不起作用嗎?我明白了
throw er; // Unhandled 'error' event
^
由此
const https = require('https');
const options = {
hostname: 'github.comx',
port: 443,
path: '/',
method: 'GET'
};
async function main() {
options.agent = new https.Agent(options);
const valid_to = await new Promise((resolve, reject) => {
try {
const req = https.request({
...options, checkServerIdentity: function (host, cert) {
resolve(cert.valid_to);
}
});
req.end();
} catch (error) {
reject(error);
};
});
return valid_to;
};
(async () => {
let a = await main();
console.log(a);
a = await main();
console.log(a);
})();
更新
在這里,我嘗試使用 try/catch,但得到
TypeError: https.request(...).then is not a function
錯誤。
async function main() {
options.agent = new https.Agent(options);
const valid_to = await new Promise((resolve, reject) => {
const req = https.request({
...options, checkServerIdentity: function (host, cert) {
resolve(cert.valid_to);
}
}).then(response => {
req.end();
}).catch(rej => {
reject(rej);
});
});
return valid_to;
};
更新 2
在這里,promise 被移到了 try 塊中,但我得到了同樣的錯誤。
async function main() {
options.agent = new https.Agent(options);
try {
const valid_to = await new Promise((resolve, reject) => {
const req = https.request({
...options, checkServerIdentity: function (host, cert) {
resolve(cert.valid_to);
}
});
req.end();
});
return valid_to;
} catch (error) {
reject(error);
};
};
uj5u.com熱心網友回復:
request是一個流,所以你應該在那里注冊錯誤偵聽器,拒絕,然后捕獲錯誤:
async function main() {
options.agent = new https.Agent(options);
const valid_to = await new Promise((resolve, reject) => {
const req = https.request({
...options, checkServerIdentity: function (host, cert) {
resolve(cert.valid_to);
}
}).on('error', (error) => {
console.error(error);
reject(error);
});
req.end();
});
return valid_to;
};
(async () => {
let a = await main().catch(err=>console.log(err));
console.log(a);
})();
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/432439.html
標籤:javascript 节点.js 异步 ecmascript-6 异步等待
上一篇:從服務器preGsonConverter訪問原始改造資料
下一篇:'()=>Promise<string>'型別的引數不能分配給'Promise<string>'型別的引數。ts(2345)
