UnhandledPromiseRejectionWarning async await - PullRequest
0 голосов
/ 30 ноября 2018

Ниже приведен мой код для функции onDisconnect на сервере graphql (apollo-server) (но не зависит от graphql).Он содержит транзакцию postgres, которая используется через адаптер DB.Код работает, но я продолжаю получать предупреждения всякий раз, когда возникают ошибки, ожидающие.Ниже мой код, а также предупреждения.Я новичок в async / await, не уверен, что сделал неправильно.

onDisconnect: () => {
    try {
        DB.tx(async t => {
                const do_something = await t.any(`SELECT *
                                                  FROM something`, []).catch((e) => { throw `error deleting socket` })
                ... more awaits here ...
                console.log(do_something)
            }
        })
    } catch (error) {
        console.log(error)
    }
},


(node:5640) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch().
(rejection id: 3)
(node:5640) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Я также попробовал следующее:

onDisconnect: () => {
    try {
        return DB.tx(async t => {
                const do_something = await t.any(`SELECT *
                                                  FROM something`, []).catch((e) => { throw `error deleting socket` })
                ... more awaits here ...
                console.log(do_something)
                return {
                    success: 1
                }
            }
        })
    } catch (error) {
        console.log(error)
        throw error
    }
},

Экспорт в качестве функции для других случаев работает без предупреждения,например:

export function do_another_thing(...) {
        try {
            return DB.tx(async t => {
                    const do_something = await t.any(`SELECT *
                                                      FROM nothing`, []).catch((e) => { throw `error fetching data` })
                    ... more awaits here ...
                    console.log(do_something)
                    return {
                        success: 1
                    }
                }
            })
        } catch (error) {
            console.log(error)
            throw error
        }
    },

1 Ответ

0 голосов
/ 30 ноября 2018

Вы должны catch await с напрямую:

 export function do_another_thing(...) {
   return DB.tx(async t => {
     try {
       const do_something = await t.any(`SELECT * FROM nothing`, []).catch((e) => { throw `error fetching data` })
       //.. more awaits here ...
       console.log(do_something)
       return {
         success: 1
       };          
    } catch(error) {
       console.log(error);
       // handle the error properly!
    }
 });

}

Подсказка: повторное смещение не выполняется ...

...