如何避免 UnhandledPromiseRejectionWarning ?
发布于 7 年前 作者 xrr20160322 4885 次浏览 来自 问答

我用 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')

然而会这样 snipaste_20170630_144031.png 但是, 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,如下代码:

async function httpsGet(url) {
    try {
        const res = await get(url)
        console.log(res)
    } catch (error) {
        console.log(error)
    }
}

2..then方法也拿不到res,不信你改成

get('https://baidu.com')
    .then(res => {
        console.log('res.data')
    })
    .catch(err => {
        console.log('err')
    })

试一下,下面是打印结果: image.png

process.on('unhandledRejection', function (err) {
	Logger.fatal(err);
});

另外,记得加全局监听。

@CRAZYFAKE 好吧, 确实不行, 输出的全是 err 里面东西, 失望.

@CRAZYFAKE 为什么文档上的 fs.stat 方法可以, https.get 不行啊? 不都是 common Node.js callback style 吗?

@xrr20160322 你说的可以是啥意思。。。

@xrr20160322 补个全的

const { promisify } = require('util')
const https = require('https'),
    http = require('http'),
    fs = require('fs');

/**
 * https.get 例子
 * @param {*} url 
 */
const get = promisify(https.get)
async function httpsGet(url) {
    try {
        const res = await get(url)
        console.log(res)
    } catch (error) {
        console.log('error', '走的这里= =')
    }
}
httpsGet('https://baidu.com')

/**
 * fs.stat 例子
 */
const fsstat = promisify(fs.stat)
async function fsstatIt() {
    try {
        const res = await fsstat('2');
        console.log(res)
    } catch (error) {
        console.log('error', '还是走的这里= =')
    }
}
fsstatIt()

@xrr20160322 我明白你啥意思了。。。。 https.get 也是callback style,但是用法上有点区别。

https.get fs.stat 你看一下

@CRAZYFAKE 不加 try catch 就可以打印结果啊

const { promisify } = require('util')
const fs = require('fs')

const stat = promisify(fs.stat)

async function callStat() {
  const stats = await stat('.')
  console.log(`哈哈! 成功了. ${stats.uid}`)
}
callStat()

snipaste_20170630_172102.png

文档上的例子就是这样的

@CRAZYFAKE 这两个的区别只是 callback 是否可选吧.

回到顶部