繁体   English   中英

UnhandledPromiseRejectionWarning:Node.JS中未处理的承诺拒绝(拒绝ID:1)

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM