简体   繁体   中英

Async node.js code (using Q) not writing to standard error

I have encountered the following problem while writing asynchronous node.js code: errors thrown inside an async block do not print anything to the console standard error , they just fail silently.

Here's a self-contained working example to recreate the issue, where I call a non-existing function outside and inside an async callback:

note the lines denoted by //! comments

var Q = require('Q');

function asyncFunc(){
    var deferred = Q.defer();

    setTimeout(function(){
        console.log('resolving promise!');
        deferred.resolve('resolveMessage');
    },2000);

    return deferred.promise;
}

asyncFunc()
    .then(function (msg) {
        nonExisting(); // ! calling here puts no error on the console
        console.log('Promise.then entered, msg:',msg);
    });

//nonExisting(); // ! calling here results in referenceError correctly printed to the console

I'm running the code from standard windows command prompt, with the node file.js command. (I'm running node 0.10.32 on Windows 7)

Why is this happening, and how can I resolve the issue?

That's an expected behaviour.

From the Q API Reference:

Since exceptions thrown in then callbacks are consumed and transformed into rejections, exceptions at the end of the chain are easy to accidentally, silently ignore.

If you want the exception to be propagated if any promise in the chain is rejected or an exception is thrown in the resolution handler, use done :

asyncFunc().done(function (msg) { nonExisting(); }); //will throw an error in the next tick
process.on('uncaughtException', console.log);

You can also chain it to another then , whose rejection handler will be executed.

asyncFunc()
    .then(function (msg) {
        nonExisting(); // ! calling here puts no error on the console
        console.log('Promise.then entered, msg:',msg);
    })
    .then(function noop () {}, console.log.bind(console, 'An error was thrown'));

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