async / await,不推荐使用未处理的拒绝承诺

时间:2018-04-05 07:06:10

标签: javascript ecmascript-6 async-await

当我使用async await函数时,我得到deprecationWarning:unhandled promise rejections are deprecated。这个错误源于在没有catch块的情况下抛出异步函数,或者拒绝未使用.catch()处理的promise。

export const publish = async (exchange, type, message) => {
        try {
            const connection = await amqplib.connect(connectionString)

            const channel = await connection.createChannel()

            channel.assertExchange(exchange, config.messageQueue.exchange.type, {durable: true})

            logger.silly(`publishing message to ${exchange}`)

            channel.publish(exchange, '', type.encode(message).finish())
        }
        catch (e) {
            logger.warn(`error while publishing message, ${e}`)

            throw e
        }
    }


    const startConsuming = async () => {
        try {
            const {Get, Sort, Cleanup, ...elasticMessages} = expectedMessages

            await init(Object.keys(elasticMessages))

            amqpService(expectedMessages, onMessage)

            publish(`${config.messageQueue.exchange.prefix}Cleanup`, contracts.televic.historyLogging.Call, '')
        } catch (e) {
            logger.error('error while establishing connection to message bus', e)
        }
    }

1 个答案:

答案 0 :(得分:2)

您之前没有input.GroupAdjacent(i => i,i=>$"Number {i}") 或之后有await

.catch

但是publish(`${config.messageQueue.exchange.prefix}Cleanup`, contracts.televic.historyLogging.Call, '')` 是一个publish函数,所以这个函数不会抛出错误,但是它返回的Promise将被拒绝并出错。因此,如果在async块中调用了throw e,那么catch会被该错误拒绝,并且不会处理此拒绝。

所以代码必须这样:

publish