【问题标题】:async/await , unhandled promise rejections are deprecatedasync/await ,不推荐使用未处理的承诺拒绝
【发布时间】:2018-09-14 21:47:46
【问题描述】:

当我使用异步等待函数时,我得到 deprecationWarning:unhandled promise rejections are deprecated。此错误源于在没有 catch 块的情况下抛出异步函数内部,或拒绝未使用 .catch() 处理的承诺。

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)
        }
    }

【问题讨论】:

  • 你有什么问题?
  • 投票以“不清楚你在问什么”结束,直到你编辑这个并包含某种实际问题。到目前为止,您只是毫无疑问地发表了一堆声明。
  • 您想解决警告吗?只需在异步函数中添加一个 .catch()
  • @Aluan Haddad 当然。我只是说添加 catch() 会(可能)解决警告。我知道这不是最好的做法
  • @Palaniichuk Dmytro,我的意思是publish.catch(() => {...})

标签: javascript ecmascript-6 async-await


【解决方案1】:

前面没有await,后面没有.catch

publish(`${config.messageQueue.exchange.prefix}Cleanup`, contracts.televic.historyLogging.Call, '')`

但是publish是一个async函数,所以这个函数不会抛出错误,但是它返回的Promise会被错误拒绝。因此,如果在 catch 块中调用 throw e,则 publish 会因该错误而被拒绝,并且不会处理此拒绝。

所以代码必须是这样的:

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

        await init(Object.keys(elasticMessages))

        amqpService(expectedMessages, onMessage)

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

【讨论】:

    猜你喜欢
    • 2019-10-13
    • 2018-09-28
    • 2020-05-23
    • 2021-10-21
    • 1970-01-01
    • 1970-01-01
    • 2019-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多