![](/img/trans.png)
[英]Node.js: Unhandled promise rejection - UnhandledPromiseRejectionWarning
[英]UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1) in Node.JS
嗨,我正在嘗試調用異步函數makeRemoteExecutableSchema
,該函數返回makeRemoteExecutableSchema
。
async function run() {
const schema = await makeRemoteExecutableSchema(
createApolloFetch({
uri: "https://5rrx10z19.lp.gql.zone/graphql"
})
);
}
我在構造函數中調用此函數。
class HelloWorld {
constructor() {
try {
run();
} catch (e) {
console.log(e, e.message, e.stack);
}
}
}
我收到此錯誤。 有誰知道如何解決這個問題?
(node:19168) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'getQueryType' of undefined
(node:19168) [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.
如果makeRemoteExecutableScheme()
返回最終拒絕的makeRemoteExecutableScheme()
,則您沒有代碼可處理該拒絕。 您可以通過以下兩種方式之一來處理它:
async function run() {
try {
const schema = await makeRemoteExecutableSchema(
createApolloFetch({
uri: "https://5rrx10z19.lp.gql.zone/graphql"
})
);
} catch(e) {
// handle the rejection here
}
}
或在這里:
class HelloWorld {
constructor() {
run().catch(err => {
// handle rejection here
});
}
}
您可以在await
和同一函數內使用try/catch
。 一個run()
返回了,您此時只是在處理一個諾言,因此您可以使用.catch()
而不是try/catch
來捕獲拒絕。
重要的是要記住, await
僅是函數中.then()
語法糖。 除了該功能之外,它不施加任何其他魔術。 一旦run()
返回,它只是返回一個常規的諾言,因此,如果您想捕獲來自該返回的諾言的拒絕,則必須對它使用.catch()
或再次await
它,然后用try/catch
包圍它。 使用try/catch
包圍未等待的promise不會捕獲您正在做的被拒絕的promise。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.