简体   繁体   English

如何处理 Node 中的 promise 拒绝?

[英]How do I handle promise rejection in Node?

I have some fairly simple code, and I can't figure out what I'm doing wrong:我有一些相当简单的代码,但我不知道我做错了什么:

  try {
    service.cache.client = await initCache();
  } catch (e) {
    console.log(e);
  }

and

const initCache = async () => {
  const options = {
    url: my_URL,
    port: my_PORT + 4
  };

  const client = await getClient(options);

  client.on('connect', (a, b) => {
    logger.info(
      `Successfully connected:  ${my_URL}:${my_PORT}`
    );
    client.connect = true;
  });

  client.on('error', (err) => Promise.reject());

  return client;
};

EDIT: I should add that in my example above, my_URL is a bogus URL that will never connect.编辑:我应该在上面的示例中补充一点, my_URL是一个永远不会连接的假 URL。 I'm trying to write some code so the app uses alternate methods when the chache client is unavailable.我正在尝试编写一些代码,以便应用程序在 chache 客户端不可用时使用替代方法。

No matter what I do, I cannot escape Unhandled Rejection warnings.无论我做什么,我都无法逃脱 Unhandled Rejection 警告。 The code above results in error: Unhandled Rejection at: Promise .上面的代码导致error: Unhandled Rejection at: Promise If I pass a new error to Promise.reject , I get the same thing.如果我将一个新错误传递给Promise.reject ,我会得到同样的结果。 If I throw my own error in the catch block, I still get error: Unhandled Rejection at: Promise .如果我在 catch 块中抛出我自己的错误,我仍然会收到error: Unhandled Rejection at: Promise What do I have to do to actually handle this rejection?我该怎么做才能真正处理这种拒绝?

EDIT: if I change client.on to client.on('error', (err) => new Error(err));编辑:如果我将client.on更改为client.on('error', (err) => new Error(err)); , the Unhandled Promise message goes away. ,未处理的 Promise 消息消失。 But I'm unable to catch this error in the catch block;但我无法在 catch 块中捕捉到这个错误; a simple console.log isn't happening.一个简单的console.log没有发生。

When using callbacks with promises you have to do a little bit of work to make them work nice together.当使用带有 Promise 的回调时,你必须做一些工作才能让它们很好地协同工作。 If I understand your intention you want to wait for the client to connect to return the promise, and in case of the event error you want to throw an error.如果我理解您的意图,您希望等待客户端连接以返回 promise,并且在发生事件error时您想抛出错误。

You have to return a new Promise like so:您必须像这样返回一个新的 Promise:

const initCache = async () => {
  const options = {
    url: my_URL,
    port: my_PORT + 4,
  };

  const client = await getClient(options);

  return new Promise((success, reject) => {
    client.on("connect", (a, b) => {
      logger.info(`Successfully connected:  ${my_URL}:${my_PORT}`);
      client.connect = true;
      success(client);
    });

    client.on("error", (err) => reject(err));
  });
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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