CNode

如何避免 UnhandledPromiseRejectionWarning ?

问答
Xxrr20160322发布于9 年前最后回复9 年前10 回复5671 浏览0 收藏

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

C
CRAZYFAKE#1·9 年前

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

Y
yansong#2·9 年前
process.on('unhandledRejection', function (err) {
	Logger.fatal(err);
});

另外,记得加全局监听。

X
xrr20160322#4·9 年前
引用 CRAZYFAKE1.async / await要加try/catch,如下代码: 2..then方法也拿不到res,不信你改成 试一下,下面是打印结果:

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

C
CRAZYFAKE#6·9 年前
引用 xrr20160322@CRAZYFAKE 为什么文档上的 fs.stat 方法可以, https.get 不行啊? 不都是 common Node.js callback style 吗?

@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()
C
CRAZYFAKE#7·9 年前
引用 xrr20160322@CRAZYFAKE 为什么文档上的 fs.stat 方法可以, https.get 不行啊? 不都是 common Node.js callback style 吗?

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

https.get fs.stat 你看一下

X
xrr20160322#8·9 年前
引用 CRAZYFAKE@xrr20160322 补个全的

@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

文档上的例子就是这样的

参与回复
登录后即可参与回复。登录