For learning Angular 2, I am trying their tutorial.
I am getting an error like this:
(node:4796) UnhandledPromiseRejectionWarning: Unhandled promise rejection (r ejection id: 1): Error: spawn cmd ENOENT
[1] (node:4796) DeprecationWarning: Unhandled promise rejections are deprecated.
In the future, promise rejections that are not handled will terminate the Node.
js process with a non-zero exit code.
I went through different questions and answers in SO but could not find out what an "Unhandled Promise Rejection" is.
Can anyone simply explain me what it is and also what Error: spawn cmd ENOENT is, when it arises and what I have to check to get rid of this warning?
The origin of this error lies in the fact that each and every promise is expected to handle promise rejection i.e. have a .catch(...) . you can avoid the same by adding .catch(...) to a promise in the code as given below.
for example, the function PTest() will either resolve or reject a promise based on the value of a global variable somevar
var somevar = false;
var PTest = function () {
return new Promise(function (resolve, reject) {
if (somevar === true)
resolve();
else
reject();
});
}
var myfunc = PTest();
myfunc.then(function () {
console.log("Promise Resolved");
}).catch(function () {
console.log("Promise Rejected");
});
In some cases, the "unhandled promise rejection" message comes even if we have .catch(..) written for promises. It's all about how you write your code. The following code will generate "unhandled promise rejection" even though we are handling catch.
var somevar = false;
var PTest = function () {
return new Promise(function (resolve, reject) {
if (somevar === true)
resolve();
else
reject();
});
}
var myfunc = PTest();
myfunc.then(function () {
console.log("Promise Resolved");
});
// See the Difference here
myfunc.catch(function () {
console.log("Promise Rejected");
});
The difference is that you don't handle .catch(...) as chain but as separate. For some reason JavaScript engine treats it as promise without un-handled promise rejection.
This is when a Promise is completed with .reject() or an exception was thrown in an async executed code and no .catch() did handle the rejection.
A rejected promise is like an exception that bubbles up towards the application entry point and causes the root error handler to produce that output.
See also
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/reject
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch
Promises can be "handled" after they are rejected. That is, one can call a promise's reject callback before providing a catch handler. This behavior is a little bothersome to me because one can write...
var promise = new Promise(function(resolve) {
kjjdjf(); // this function does not exist });
... and in this case, the Promise is rejected silently. If one forgets to add a catch handler, code will continue to silently run without errors. This could lead to lingering and hard-to-find bugs.
In the case of Node.js, there is talk of handling these unhandled Promise rejections and reporting the problems. This brings me to ES7 async/await. Consider this example:
async function getReadyForBed() {
let teethPromise = brushTeeth();
let tempPromise = getRoomTemperature();
// Change clothes based on room temperature
let temp = await tempPromise;
// Assume `changeClothes` also returns a Promise
if(temp > 20) {
await changeClothes("warm");
} else {
await changeClothes("cold");
}
await teethPromise;
}
In the example above, suppose teethPromise was rejected (Error: out of toothpaste!) before getRoomTemperature was fulfilled. In this case, there would be an unhandled Promise rejection until await teethPromise.
My point is this... if we consider unhandled Promise rejections to be a problem, Promises that are later handled by an await might get inadvertently reported as bugs. Then again, if we consider unhandled Promise rejections to not be problematic, legitimate bugs might not get reported.
Thoughts on this?
This is related to the discussion found in the Node.js project here:
Default Unhandled Rejection Detection Behavior
if you write the code this way:
function getReadyForBed() {
let teethPromise = brushTeeth();
let tempPromise = getRoomTemperature();
// Change clothes based on room temperature
return Promise.resolve(tempPromise)
.then(temp => {
// Assume `changeClothes` also returns a Promise
if (temp > 20) {
return Promise.resolve(changeClothes("warm"));
} else {
return Promise.resolve(changeClothes("cold"));
}
})
.then(teethPromise)
.then(Promise.resolve()); // since the async function returns nothing, ensure it's a resolved promise for `undefined`, unless it's previously rejected
}
When getReadyForBed is invoked, it will synchronously create the final (not returned) promise - which will have the same "unhandled rejection" error as any other promise (could be nothing, of course, depending on the engine). (I find it very odd your function doesn't return anything, which means your async function produces a promise for undefined.
If I make a Promise right now without a catch, and add one later, most "unhandled rejection error" implementations will actually retract the warning when i do later handle it. In other words, async/await doesn't alter the "unhandled rejection" discussion in any way that I can see.
to avoid this pitfall please write the code this way:
async function getReadyForBed() {
let teethPromise = brushTeeth();
let tempPromise = getRoomTemperature();
// Change clothes based on room temperature
var clothesPromise = tempPromise.then(function(temp) {
// Assume `changeClothes` also returns a Promise
if(temp > 20) {
return changeClothes("warm");
} else {
return changeClothes("cold");
}
});
/* Note that clothesPromise resolves to the result of `changeClothes`
due to Promise "chaining" magic. */
// Combine promises and await them both
await Promise.all(teethPromise, clothesPromise);
}
Note that this should prevent any unhandled promise rejection.
"DeprecationWarning: Unhandled promise rejections are deprecated"
TLDR: A promise has resolve and reject, doing a reject without a catch to handle it is deprecated, so you will have to at least have a catch at top level.
In my case was Promise with no reject neither resolve, because my Promise function threw an exception. This mistake cause UnhandledPromiseRejectionWarning message.
I was seeing this when I had a util file with a Promised API call, a component that calls it but wasn't explicitly handling the .catch, and a Jest that was mocking up a Promise.reject:
fetchStuff.mockImplementationOnce(() => Promise.reject(new Error('intentional fail')));
Furthermore, this was poisoning my mock, so that even though I was calling jest.resetAllMocks() before each test, the very next test would try render and that render would call the API, and it would fail. The test after would be back to a good state. I could swap around the order of my tests to prove that it would always poison the next render.
I tried handling the error in the API, but didn't succeed. I tried handling in my Jest mock, but that didn't work, either. What I ended up having to do was explicitly handle the .catch in my component.
I had faced a similar issue with NodeJS, where the culprit was a forEach loop. Note that forEach is a synchronous function (NOT Asynchronous). Therefore it just ignores the promise returned.
The solution was to use a for-of loop instead:
Code where I got the error:
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()
is as follows:
permissionOrders.forEach( async(order) => {
const requestPermissionOrder = new RequestPermissionOrderSchema({
item: order.item,
item_desc: order.item_desc,
quantity: order.quantity,
unit_price: order.unit_price,
total_cost: order.total_cost,
status: order.status,
priority: order.priority,
directOrder: order.directOrder
});
try {
const dat_order = await requestPermissionOrder.save();
res.json(dat_order);
} catch(err){
res.json({ message : err});
}
});
Solution for the above issue is as follows:
for (let order of permissionOrders){
const requestPermissionOrder = new RequestPermissionOrderSchema({
item: order.item,
item_desc: order.item_desc,
quantity: order.quantity,
unit_price: order.unit_price,
total_cost: order.total_cost,
status: order.status,
priority: order.priority,
directOrder: order.directOrder
});
try {
const dat_order = await requestPermissionOrder.save();
res.json(dat_order);
} catch(err){
res.json({ message : err});
}
};
Try not closing the connection before you send data to your database. Remove client.close(); from your code and it'll work fine.
When I instantiate a promise, I'm going to generate an asynchronous function. If the function goes well then I call the RESOLVE then the flow continues in the RESOLVE handler, in the THEN. If the function fails, then terminate the function by calling REJECT then the flow continues in the CATCH.
In NodeJs are deprecated the rejection handler. Your error is just a warning and I read it inside node.js github. I found this.
DEP0018: Unhandled promise rejections
Type: Runtime
Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I'm using a 3rd parth library to make an async call in my nodejs backend code. There's an unhandled promise rejection coming from this call which I'm having trouble catching. (It brings down my node app.)
Based on the input passed, it's expected to fail sometimes:
exports.getSomeData = (input) => {
console.log('GETTING DATA...')
return ThirdPartyLib.makeAsyncCall(input).then((result) => {
console.log('SUCCESS');
return result;
},(rejection) => {
console.log('REJECTED');
return {};
}).catch(error => {
console.log('ERROR');
return {};
});
}
But none of the REJECTED/ERROR messages print when it fails. I just see a console message from the lib: Unhandled rejection at: Promise and my app goes down.
Am I missing anything in the way I handle the non-happy path?
Is it possible for the library code to do something that the above WOULDN'T catch?
Is it possible for the library code to do something that the above WOULDN'T catch?
Sure, it just has to create a Promise (e.g. by calling an async function) without chaining it into the promise chain (aka without awaiting it):
async makeAsyncCall(data) {
Promise.reject("Possible");
}
So yes, the library you are using should either await that detached promise or it should attach an error handler to it (and handle / purposely ignore the error). It's not your fault.
Aside from the double rejection handler (which is pointless, just use catch()), your code should just work.
So given that you are seeing that error, this means that the library you are using has a bug.
I was having issues running a test (in Node),
I was simulating a promise being rejected, and my code should retry (using promise-retry if that could be relevant).
When I simulated the rejected promise using stub.returns(Promise.reject(error)
I was getting a uncaught error warnings (for my dummyErrors), even though I am catching errors where I call my function...
-note, these uncaught errors were only happening in the unit tests not in real calls.
const mockedFunction = sinon.stub();
const dummyError = new Error('Document is locked');
mockedFunction.onCall(0).returns(Promise.reject(dummyError));
mockedFunction.onCall(0).returns(Promise.reject(dummyError));
mockedFunction.onCall(0).returns(Promise.reject(dummyError));
mockedFunction.onCall(1).returns(Promise.resolve({approved: true}));
I discovered that by changing to use the stub.rejects() syntax:
mockedFunction.onCall(0).rejects(dummyError);
mockedFunction.onCall(1).rejects(dummyError);
mockedFunction.onCall(2).rejects(dummyError));
mockedFunction.onCall(3).resolves({approved: true});
I no longer get the uncaught error warnings.
My issue is solved, however I would like to get a better understand as to why, I looked at the sinon source code and it looks like the implementation of .rejects is no different
In promise implementations that are intrinsically detect uncaught error (including V8/Node.js), an error from rejected promise should be caught on same tick, otherwise it triggers UnhandledPromiseRejectionWarning.
This will work fine:
let promise = Promise.reject();
promise.catch(() => {});
This will result in potentially unhandled promise and trigger a warning:
let promise = Promise.reject();
setTimeout(() => {
promise.catch(() => {});
});
If Promise.reject(dummyError) isn't chained with catch(...) or then(..., ...) on same tick, it triggers a warning, while in case of rejects(dummyError) a rejected promise is created on function call, so this likely will be true:
sinon.spy(Promise, 'reject');
mockedFunction.onCall(0).rejects(dummyError);
expect(Promise.reject).to.have.not.been.called;
mockedFunction();
expect(Promise.reject).to.have.been.called;
An alternative to rejects(dummyError) is:
mockedFunction.onCall(0).callsFake(() => Promise.reject(dummyError))
Below is my code. Test-case is getting passed whether my actual is equal to expected or not equal.It is just showing warning message when it is not equal but my test-case is shown in green .I cant see any failure message in report.
Code:
this.VerifyAccountHolder=async function(){
var testPromise = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve(elementAccount.isPresent());
}, 200);
});
var result = await testPromise;
assert.equal(result,true,"wrong result");
Warning message:
(node:8784) UnhandledPromiseRejectionWarning: Unhandled promise
rejection (rejection id: 1): AssertionError: expected false to equal
true (node:8784) [DEP0018] DeprecationWarning: Unhandled promise
rejections are deprecated. In the future, promise rejections that are
not handled will terminate the Nodejs process with a non-zero exit
code.
how to avoid this warning
I want to display the assertion error in report.I'm new to JavaScript protractor framework.
You could simplify this whole function by removing the promise entirely. I'm really not sure why you need setTimeout either. The element is going to present or it isn't. You could probably use ExpectedConditions.presenceOf() with browser.wait() but this seems redundant to me. As much as I hate to suggest this, if you REALLY must wait for 200ms before checking the element is present just use browser.sleep(). I would use this as a last resort though. Try getting it to work without any explicit waits if you can.
this.VerifyAccountHolder = function() {
browser.sleep(200); //only use this if you REALLY need it
return elementAccount.isPresent();
});
And then you should move the assertion to a test instead of keeping it in this function.
it('should be present', async () => {
let result = await pageObjectName.VerifyAccountHolder();
expect(result).toEqual(true);
//or if you prefer to keep using a node assertion instead
//assert.equal(result,true,"element not present");
});
I'm currently reading "YKDJS - Async & Performance" by Kyle Simpson, in particular Chapter 3 - Promises.
The author says that any Promise for which no rejection handler is registered receives a default one:
let p = new Promise(function(resolve, reject) { resolve("Yay!"); });
p.then(
function(val) { /* Do whatever */ }
/* Default rejection handler
, function(e) { throw e; } */
);
Later in the chapter he claims that one problem with the way Promises are designed is the following:
In any Promise chain, any error that happens in one of the handler functions of the last Promise in the chain is just "swallowed" instead of being reported.
He proposes to change the way Promises work so that any Promise that doesn't have a rejection handler reports the error by throwing a global error. Then he proposes a theoretical Promise#defer() function one could use on a Promise to prevent this reporting behavior.
Now my question is: How do these two go together? It's true that any Promisethat doesn't have a rejection handler receives a default one which just throws the rejection value as a global error:
Promise.reject("Oops");
/* VM668:1 Uncaught (in promise) Oops */
So already Promises seem to work in just the way he proposes.
Am I misunderstanding something? Thanks for any help.
The Uncaught Handling he mentions in
Some Promise libraries have added methods for registering something
like a "global unhandled rejection" handler, which would be called
instead of a globally thrown error. But their solution for how to
identify an error as "uncaught" is to have an arbitrary-length timer,
say 3 seconds, running from time of rejection. If a Promise is
rejected but no error handler is registered before the timer fires,
then it's assumed that you won't ever be registering a handler, so
it's "uncaught."
In practice, this has worked well for many libraries, as most usage
patterns don't typically call for significant delay between Promise
rejection and observation of that rejection.
has been standardised as unhandled rejection warnings (not using an arbitrary timer, but firing right away). It does indeed work quite well.
He also states in Chapter 4 of ES6 & Beyond
[When] we are not listening for that rejection, […] it will be
silently held onto for future observation. If you never observe it by
calling a then(..) or catch(..), then it will go unhandled. Some
browser developer consoles may detect these unhandled rejections and
report them, but this is not reliably guaranteed; you should always
observe promise rejections.