简体   繁体   中英

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. I'm trying to write some code so the app uses alternate methods when the chache client is unavailable.

No matter what I do, I cannot escape Unhandled Rejection warnings. The code above results in error: Unhandled Rejection at: Promise . If I pass a new error to Promise.reject , I get the same thing. If I throw my own error in the catch block, I still get 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)); , the Unhandled Promise message goes away. But I'm unable to catch this error in the catch block; a simple console.log isn't happening.

When using callbacks with promises you have to do a little bit of work to make them work nice together. 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.

You have to return a new Promise like so:

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));
  });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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