如何避免 UnhandledPromiseRejectionWarning ?
发布于 8 年前 作者 xrr20160322 5533 次预览 最后一次回复是 8 年前 来自 问答
我用 util.promisify() 包装了 https.get() 方法, 按文档上说的可以这样写
const { promisify } = require('util')
const https = require('https')
const get = promisify(https.get)
// get.catch = () => {}
async function httpsGet(url) {
const res = await get(url)
// res.catch(() => {})
console.log(res)
}
httpsGet('https://baidu.com')
然而会这样
但是, then 写法就能得到结果
get('https://baidu.com')
.then(res => {
console.log(res.data)
})
.catch(err => {
console.log(err)
})
这是为何? node v8.1.2
10 回复
1.
async / await要加try/catch,如下代码:2.
.then方法也拿不到res,不信你改成试一下,下面是打印结果:
另外,记得加全局监听。
@CRAZYFAKE 好吧, 确实不行, 输出的全是 err 里面东西, 失望.
@CRAZYFAKE 为什么文档上的
fs.stat方法可以,https.get不行啊? 不都是 common Node.js callback style 吗?@xrr20160322 你说的
可以是啥意思。。。@xrr20160322 补个全的
@xrr20160322 我明白你啥意思了。。。。
https.get也是callback style,但是用法上有点区别。https.get fs.stat 你看一下
@CRAZYFAKE 不加 try catch 就可以打印结果啊
文档上的例子就是这样的
@CRAZYFAKE 这两个的区别只是 callback 是否可选吧.
@xrr20160322 是的。