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");
});
Related
I am not knowledgeable in NodeJS or JS so bare that in mind. I have been playing around with a radix trie module Merkle-Patricia-Tree and it's taken me down a rabbit hole when using a level module similar to Google's leveldb to store the radix trie in persistent storage.
what I think I know:
The Merkle-Patricia-Tree module requires a levelup dependency which wraps level down as the first parameter when instantiating a new trie
Seems to write to the store with trie.put(key,value), but having problems reading with trie.get(key)
In one of the error files in Markle-Patricia-Trie library...
constructor(leveldb) {
this._leveldb = leveldb !== null && leveldb !== void 0 ? leveldb : level();
}
does pass in the levelup(leveldown('path')) when instantiating trie with db but somehow says that here in the same file (included affected files)...
async get(key) {
let value = null;
try {
value = await this._leveldb.get(key, exports.ENCODING_OPTS);
}
catch (error) {
if (error.notFound) {
// not found, returning null
}
else {
throw error;
}
}
return value;
}
this...
(node:17128) UnhandledPromiseRejectionWarning: TypeError: this._leveldb.get is not a function
at CheckpointDB.get (\cryptoNetwork\node_modules\merkle-patricia-tree\dist\db.js:27:41)
at CheckpointDB.get (\cryptoNetwork\node_modules\merkle-patricia-tree\dist\checkpointDb.js:85:35)
at SecureTrie.lookupNode (\cryptoNetwork\node_modules\merkle-patricia-tree\dist\baseTrie.js:250:31)
at SecureTrie._lookupNode (\cryptoNetwork\node_modules\merkle-patricia-tree\dist\baseTrie.js:266:21)
at \cryptoNetwork\node_modules\merkle-patricia-tree\dist\util\walkController.js:41:40
at new Promise (<anonymous>)
at WalkController.startWalk (\cryptoNetwork\node_modules\merkle-patricia-tree\dist\util\walkController.js:36:22)
at Function.newWalk (\cryptoNetwork\node_modules\merkle-patricia-tree\dist\util\walkController.js:32:24)
at SecureTrie.walkTrie (\cryptoNetwork\node_modules\merkle-patricia-tree\dist\baseTrie.js:221:47)
at \cryptoNetwork\node_modules\merkle-patricia-tree\dist\baseTrie.js:200:28
(node:17128) 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(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:17128) [DEP0018] 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.
The encoding is dealt with properly so assume under that axiom
aggregator code:
testing()
{
programData.volatile.modularVariables.action = 'read';
programData.volatile.modularVariables.user = 'blahblahblahblah';
programData.volatile.modularVariables.createTrie();
};
object with relevant code (I'm aware of extra unneeded code, editing time of writing this)
//assume object containing these functions/variables inside
user: '-', //aggregator initializes this and action
action: '-',
createTrie: ()=>{switch(programData.volatile.modularVariables.action){case 'read':programData.volatile.modularVariables.read(programData.persistent.paths.srcRoot,programData.volatile.modularVariables.encoding.utf8,programData.volatile.modularVariables.handleTrie);break;case 'write':programData.volatile.modularVariables.read(programData.persistent.paths.srcRoot,programData.volatile.modularVariables.encoding.utf8,programData.volatile.modularVariables.handleTrie);break;case 'new':programData.volatile.modularVariables.newTrie(db);break;default: console.log(`%c${programData.volatile.debug.debugStrings.errCodes.createTrie}: Error with action selection`,'color: red');}},
handleTrie: async (err,data)=>{var userBIN = Buffer.from(programData.volatile.modularVariables.user); var root=Buffer.from(data,programData.volatile.modularVariables.encoding.hex);console.log(root); switch(programData.volatile.modularVariables.action){case 'read': const trie = new merkle_patricia_tree_1.SecureTrie(programData.persistent.paths.srcRoot,root);
var result = await trie.get(userBIN); console.log(result)}},
read: (file,encoding,cb)=>{fs.readFile(file,encoding,cb)},
encoding: {utf8:'utf8',hex:'hex',base64:'base64',BIN:(data,encoding)=>{Buffer.from(data,encoding)}}, //Depricate BIN asap,
srcRoot: './vortex/root.txt',
conclusion
I am stumped, I am not sure what I am doing wrong or what is wrong with Markle-Patricia-Trie (or the leveldb). My questions are, what am I doing wrong? Can you explain to me what's wrong?. Thank you :).
In the handleTrie arrow function I used as callback for the read arrow function, I passed in the path of the store, not the level instance itself...
Every time a message is sent in a specific channel, I want to print it to the console (with console.log). I am also going to color it with npm install colors. I go everywhere, even on Stack Overflow, but I cannot seem to find any information. I am coding a Scholastic Bowl-helping bot. Below is the code I have tried (I found this on Stack Overflow.)
message.fetch({ limit: 1 }).then(messages => {
let lastMessage = message.first();
if (message.channel.lastMessage = 'channel-id'){
console.log(lastMessage.red);
}
})
(Note that when I say 'channel-id' I mean the actual ID of the channel.)
The error I am getting is that message.first is not a thing.
How do I fix this error, and how can I get the most recent message in discord.js?
Edit: The exact error I got is this:
(node:12352) UnhandledPromiseRejectionWarning: TypeError: messages.first is not a function
at C:\Users\[user redacted]\Desktop\SchoBot\index.js:57:32
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:12352) 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(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:12352) [DEP0018] 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.
Below is the edit for the 3rd comment on this question (sorted by oldest):
message.channel.fetch({ limit: 1 }).then(messages => {
let lastMessage = message.channel.first();
if (message.channel.lastMessage = 'channel-id'){
console.log(lastMessage.red);
}
})
Use message.channel.messages.fetch() instead of message.channel.fetch().
I didn't find the message.first function in the discord.js documentation, so I am not sure if it works. But you don't really need that function to fetch a message. The fetch function already did that for you.
In your case, the option limit: 1 will only return the most recent message, which is the command you use to trigger the fetch. If you want to fetch the most recent message but not your command, you should use limit: 2 instead and remove your command in the object later.
The fetch function will return an object containing message id and the content.
I assume that message.fetch needs to be message.channel.fetch
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 am trying to make a Node.js bot, so I found a module, installed it and tried out its example code.
Now, I have an async function that loads some text from an API. This is the code:
(async () => {
// Display user's balance
balance = kraken.api('Balance');
console.log(await balance);
})();
When I run the code above, this is what I get in commandprompt:
{
error: [],
result: { A: '2.0', BC: '0.005', BCA: '111' }
}
How would I be able to make it only log a specific part of this, which looks like an array?
I've tried doing stuff like (to get it to return 2.0):
console.log(await balance.result.A)
But that does not seem to work as it returns this:
(node:6604) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'A' of undefined
(node:6604) [DEP0018] 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.
Out of ideas and need help.. Thanks!
You habe to put your await statement in parentheses, like this:
console.log((await balance).result.A);
This will fetch the balance asynchronously, then log the result property.
I have just installed Node v7.2.0 and learned that the following code:
var prm = Promise.reject(new Error('fail'));
results in this message:;
(node:4786) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: fail
(node:4786) 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 understand the reasoning behind this as many programmers have probably experienced the frustration of an Error ending up being swallowed by a Promise. However then I did this experiment:
var prm = Promise.reject(new Error('fail'));
setTimeout(() => {
prm.catch((err) => {
console.log(err.message);
})
},
0)
which results in:
(node:4860) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: fail
(node:4860) 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.
(node:4860) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)
fail
I on basis of the PromiseRejectionHandledWarning assume that handling a Promise rejection asynchronously is/might be a bad thing.
But why is that?
Note: See 2020 updates below for changes in Node v15
"Should I refrain from handling Promise rejection asynchronously?"
Those warnings serve an important purpose but to see how it all works see those examples:
Try this:
process.on('unhandledRejection', () => {});
process.on('rejectionHandled', () => {});
var prm = Promise.reject(new Error('fail'));
setTimeout(() => {
prm.catch((err) => {
console.log(err.message);
})
}, 0);
Or this:
var prm = Promise.reject(new Error('fail'));
prm.catch(() => {});
setTimeout(() => {
prm.catch((err) => {
console.log(err.message);
})
}, 0);
Or this:
var caught = require('caught');
var prm = caught(Promise.reject(new Error('fail')));
setTimeout(() => {
prm.catch((err) => {
console.log(err.message);
})
}, 0);
Disclaimer: I am the author of the caught module (and yes, I wrote it for this answer).
Rationale
It was added to Node as one of the Breaking changes between v6 and v7. There was a heated discussion about it in Issue #830: Default Unhandled Rejection Detection Behavior with no universal agreement on how promises with rejection handlers attached asynchronously should behave - work without warnings, work with warnings or be forbidden to use at all by terminating the program. More discussion took place in several issues of the unhandled-rejections-spec project.
This warning is to help you find situations where you forgot to handle the rejection but sometimes you may want to avoid it. For example you may want to make a bunch of requests and store the resulting promises in an array, only to handle it later in some other part of your program.
One of the advantages of promises over callbacks is that you can separate the place where you create the promise from the place (or places) where you attach the handlers. Those warnings make it more difficult to do but you can either handle the events (my first example) or attach a dummy catch handler wherever you create a promise that you don't want to handle right away (second example). Or you can have a module do it for you (third example).
Avoiding warnings
Attaching an empty handler doesn't change the way how the stored promise works in any way if you do it in two steps:
var prm1 = Promise.reject(new Error('fail'));
prm1.catch(() => {});
This will not be the same, though:
var prm2 = Promise.reject(new Error('fail')).catch(() => {});
Here prm2 will be a different promise then prm1. While prm1 will be rejected with 'fail' error, prm2 will be resolved with undefined which is probably not what you want.
But you could write a simple function to make it work like a two-step example above, like I did with the caught module:
var prm3 = caught(Promise.reject(new Error('fail')));
Here prm3 is the same as prm1.
See: https://www.npmjs.com/package/caught
2017 Update
See also Pull Request #6375: lib,src: "throw" on unhandled promise rejections (not merged yet as of Febryary 2017) that is marked as Milestone 8.0.0:
Makes Promises "throw" rejections which exit like regular uncaught errors. [emphasis added]
This means that we can expect Node 8.x to change the warning that this question is about into an error that crashes and terminates the process and we should take it into account while writing our programs today to avoid surprises in the future.
See also the Node.js 8.0.0 Tracking Issue #10117.
2020 Update
See also Pull Request #33021: process: Change default --unhandled-rejections=throw (already merged and released as part of the v15 release - see: release notes) that once again makes it an exception:
As of Node.js 15, the default mode for unhandledRejection is changed to throw (from warn). In throw mode, if an unhandledRejection hook is not set, the unhandledRejection is raised as an uncaught exception. Users that have an unhandledRejection hook should see no change in behavior, and it’s still possible to switch modes using the --unhandled-rejections=mode process flag.
This means that Node 15.x has finally changed the warning that this question is about into an error so as I said in 2017 above, we should definitely take it into account while writing our programs because if we don't then it will definitely cause problems when upgrading the runtime to Node 15.x or higher.
I assume that handling a Promise rejection asynchronously is a bad thing.
Yes indeed it is.
It is expected that you want to handle any rejections immediately anyway. If you fail to do (and possibly fail to ever handle it), you'll get a warning.
I've experienced hardly any situations where you wouldn't want to fail immediately after getting a rejection. And even if you need to wait for something further after the fail, you should do that explicitly.
I've never seen a case where it would be impossible to immediately install the error handler (try to convince me otherwise). In your case, if you want a slightly delayed error message, just do
var prm = Promise.reject(new Error('fail'));
prm.catch((err) => {
setTimeout(() => {
console.log(err.message);
}, 0);
});