gpt4 book ai didi

javascript - UnhandledPromiseRejectionWarning 异步等待

转载 作者:行者123 更新时间:2023-11-29 16:00:47 26 4
gpt4 key购买 nike

以下是我在 graphql(apollo-server)服务器中的 onDisconnect 函数代码(但不是特定于 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 as function 在没有警告的情况下工作,例如:

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

最佳答案

你必须直接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!
}
});

}

提示:重新抛出不是处理...

关于javascript - UnhandledPromiseRejectionWarning 异步等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53559973/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com