我正在使用 ES2017 的 await
关键字,以及 util.promisify()
将 https.get()
与 await< 一起使用
.
使用以下代码测试连接到 HTTPS:
const util = require('util'),
https = require('https'),
httpsGet = util.promisify(https.get);
var start = async function(){
try {
var res = await httpsGet('https://github.com')
} catch(err) {
console.log('>>>>>>>CAUGHT AN ERROR>>>>>>', err.message)
}
console.log('FINISHED')
}
start()
返回:
>>>>>>>CAUGHT AN ERROR>>>>>> undefined
我怀疑我的代码已损坏,但我不确定如何损坏。 我怎样才能得到真正的错误?
更新:根据要求,仅记录 err 而不是 err.message:
>>>>>>>CAUGHT AN ERROR - RAW ERR>>>>>> IncomingMessage {
_readableState:
ReadableState {
objectMode: false,
highWaterMark: 16384,
buffer: BufferList { head: null, tail: null, length: 0 },
length: 0,
pipes: null,
pipesCount: 0,
flowing: null,
ended: false,
endEmitted: false,
reading: false,
最佳答案
https.get
的回调 does not have an err
option 。它是一个流 - 错误通过 .on(error)
处理。因此它没有 err
回调,并且不能与 util.promisify()
显示 err
的唯一原因是 res
是回调的最后一项 - promisify
预计会出现错误。所以这里抛出的err
实际上是一个res
流。
但是你可以从 https.get 做出 promise ,而不需要 util.promisify:
function httpsGet(option) {
return new Promise( (resolve, reject) => {
let request = https.get( option, (response) => {
if (response.statusCode < 200 || response.statusCode > 299) {
reject( new Error('Failed to load page'+response.statusCode) );}
let data = "";
response.on( 'data', (chunk) => data += chunk );
response.on( 'end', () => resolve(JSON.parse(data)) );
} );
request.on( 'error', (err) => reject(err) );
})
}
关于javascript - promisfying https.get 后出现 no 'message' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44968769/