I'm aware of existing answers to issues involving UnhandledPromiseRejectionWarning
on SO, but none of the found ones seems to be matching my case sufficiently. Basically, I thought I know how to handle promises. But this case is driving me nuts and so I'd like to ask for some support here: How to get rid of that warning?
I am implementing some writable stream in NodeJS with the following implementation of _write()
:
_write( data, encoding, doneFn ) {
Promise.race( [
this.getSocket(),
new Promise( ( resolve, reject ) => {
setTimeout( reject, 1000, Object.assign( new Error( `timeout on trying to connect w/ ${this.address}` ), { code: "ECONNREFUSED" } ) );
} ),
] )
.then( socket => {
if ( socket ) {
return new Promise( ( resolve, reject ) => {
socket.once( "error", reject );
socket.write( data, encoding, () => {
socket.removeListener( "error", reject );
resolve();
} );
} );
}
} )
.then( doneFn )
.catch( error => {
const { address } = this;
switch ( error.code ) {
case "EPIPE" :
case "ECONNRESET" :
Log( `lost connection w/ ${address.id}` );
break;
case "ECONNREFUSED" :
Log( `failed to connect w/ ${address.id}` );
break;
}
console.log( "error is", error.message );
doneFn( error );
} );
}
When I test this code for properly emitting error on timeout I get the mysterious UnhandledPromiseRejectionWarning
.
error is timeout on trying to connect w/ /ip4/127.0.0.1/tcp/1
(node:5052) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: timeout on trying to connect w/ /ip4/127.0.0.1/tcp/1
Since _write()
is working w/o promises by design I am pretty sure this warning is due to the code given here. But I can't figure out how to get rid of the warning. Even attaching catch-handler explicitly didn't suppress it.
UPDATE: Code has been refactored and re-tested. Rejection warning is logged nonetheless. I was using NodeJS 6.11 first, but this time it's 8.11.