N S*_*rma 2 javascript node.js async-await
嗨,我试图调用异步函数makeRemoteExecutableSchema,它返回promise.
async function run() {
const schema = await makeRemoteExecutableSchema(
createApolloFetch({
uri: "https://5rrx10z19.lp.gql.zone/graphql"
})
);
}
Run Code Online (Sandbox Code Playgroud)
我在构造函数中调用此函数.
class HelloWorld {
constructor() {
try {
run();
} catch (e) {
console.log(e, e.message, e.stack);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我收到了这个错误.有谁知道如何解决这个问题?
(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.
Run Code Online (Sandbox Code Playgroud)
如果makeRemoteExecutableScheme()返回最终拒绝的承诺,那么您没有代码来处理拒绝.您可以通过以下两种方式之一处理它:
async function run() {
try {
const schema = await makeRemoteExecutableSchema(
createApolloFetch({
uri: "https://5rrx10z19.lp.gql.zone/graphql"
})
);
} catch(e) {
// handle the rejection here
}
}
Run Code Online (Sandbox Code Playgroud)
或者在这里:
class HelloWorld {
constructor() {
run().catch(err => {
// handle rejection here
});
}
}
Run Code Online (Sandbox Code Playgroud)
您可以try/catch在await同一个函数中使用.一个run()人回来了,你只是在那个时候处理一个承诺,所以你会抓住那里的拒绝.catch(),而不是try/catch.
重要的是要记住,仅在函数内await是语法糖.then().除了该功能之外,它不会应用任何魔法.一旦run()返回,它只是返回一个常规的承诺,所以如果你想要从那个返回的承诺中捕获拒绝,你必须使用.catch()它或await它再次使用它然后包围它try/catch.围绕着一个期待已久的承诺try/catch并没有抓住被拒绝的承诺,而这正是你所做的.
| 归档时间: |
|
| 查看次数: |
3449 次 |
| 最近记录: |