Skip to content

Promise - unhandled rejection warning has been thrown, although the rejection seems to be handled #1208

Description

  • Node.js Version: v9.11.1
  • OS: windows 10
  • Scope (install, code, runtime, meta, other?): ?
  • Module (and version) (if relevant): ???

We have a code like this

'use strict';

var a = new Promise((res, rej) => {
  rej(123);
  console.log('not ok');
});

a.then(() => console.log(1));
a.catch(a => console.log(a));

The output is following:

> node example.js
not ok
123
(node:4748) UnhandledPromiseRejectionWarning: 123
(node:4748) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This
error originated either by throwing inside of an async function without a catch
block, or by rejecting a promise which was not handled with .catch(). (rejection
 id: 2)
(node:4748) [DEP0018] DeprecationWarning: Unhandled promise rejections are depre
cated. In the future, promise rejections that are not handled will terminate the
 Node.js process with a non-zero exit code.

So we are confused about why this happens:

  1. Why is not ok printed before 123?
  2. Why do we get unhandled warning while the rejection is handled (it has catch properly attached)?
  3. How to do it properly (to avoid warning and to reject silently)?

Sorry if this question is noobish, can't figure out how to do this for a week. Tried stack overflow, but got no response and no votes at all, the post is ignored completely

Activity

  1. ryzokuken commented on Apr 11, 2018

    @ryzokuken

    @user8322 no question is noobish, and if it's troubling you then you should ask out without thinking too much about it :)

    Regarding 2 and 3, the unhandled warning came up because it was, in fact, not handled properly, because you tried handling success and failure at different statements. The correct code would be:

    'use strict';
    
    var a = new Promise((res, rej) => {
      rej(123);
      console.log('not ok');
    });
    
    a
      .then(() => console.log(1))
      .catch(a => console.log(a));
    
    // or just .then(...).catch(...) on the same line, but this way it's more readable

    and indeed, this work. See for yourself.

    Regarding 1, this happens because of how Node.js works and it's internals (as well as v8's). To get started with promises (regarding syntax and internals), try out nodeschool's workshop, "Promise it won't hurt" at https://github.com/stevekane/promise-it-wont-hurt

  2. ghost closed this as completedon Apr 11, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions