want to store promise value in an array - protractor

I want to get all the values from a registration page and store all values in an array. How can I do that in protractor?
var arr = new Array(); //declare array
InputName.getAttribute("value")
.then(function(value){
arr[0]=value; // want to store promise value in an array
});
console.log(arr[0]);

If you run your code, it will first log arr[0] and then resolve Promise. Therefore, you may access that array's values in the next Promise. Something like this
var arr = new Array(); // <- this is by the way bad practice, use 'let arr = [];'
InputName.getAttribute("value")
.then(function(value) {
arr[0]=value; // I would use arr.push(value)
});
anotherInput.getAttribute("value")
.then(function(value) {
console.log(arr[0]); // your value should be accessible here
arr.push(value) // push another value
});
But, honestly, I've been working with Protractor fo a while now and I still have difficulties understanding promises... This why I'm using async/await in my tests so if I were to implement something like that I would end up having the following
let arr = [];
let value1 = await InputName.getAttribute("value");
arr.push(value1);
console.log(arr[0]);
Clear, neat code with no hustle. Plus protractor team is actually removing promise_manager, so one day when you update it your code will not work anymore. Then why not switch earlier

Related

Call a PostgreSQL function and get result back with no loop

I have a simple rust program that interacts with a PostgreSQL database.
The actual code is:
for row in &db_client.query("select magic_value from priv.magic_value();", &[]).unwrap()
{
magic_value = row.get("magic_value");
println!("Magic value is = {}", magic_value);
}
And.. it works. But I don't like it: I know this function will return one and only one value.
From the example I found, for example here: https://docs.rs/postgres/latest/postgres/index.html
and here: https://tms-dev-blog.com/postgresql-database-with-rust-how-to/
You always have a recordset to loop on.
Which is the clean way to call a function without looping?
query returns a Result<Vec<Row>, _>. You are already unwrapping the Vec, so you can just use it directly instead of looping. By turning the Vec into an owning iterator yourself, you can even easily obtain a Row instead of a &Row.
magic_value = db_client.query("select magic_value from priv.magic_value();", &[])
.unwrap() // -> Vec<Row>
.into_iter() // -> impl Iterator<Item=Row>
.next() // -> Option<Row>
.unwrap() // -> Row
.get("magic_value");

MongoDB countDocuments() is returning an object, not a number

I'm starting to learn about mongoose/MongoDB aggregation functions, and am having some basic difficulties. For example, I'm trying to do the following:
var myModels= require('./models/myModel');
var myCount = myModels.countDocuments({userID: "A"});
console.log(myCount );
I just want to count the number of documents with userID of "A" but when this prints to the console, it's printing as a whole object, instead of just a numerical count. I've read the answer here but I'm still not able to solve this problem (also, is there a way, unlike in that question, to return the count directly rather than having to predefine a variable and set it in a callback function?)
I'm trying to follow the guide here and don't see where I'm going wrong.
It's because the return value of countDocuments is a promise and not a number.
You either need to wait for that Promise or use callback syntax like so:
var myModels= require('./models/myModel');
// this required the code to be inside an async function
var myCount = await myModels.countDocuments({userID: "A"});
console.log(myCount);
Or:
var myModels= require('./models/myModel');
myModels.countDocuments({userID: "A"})
.then((myCount) =>{console.log(myCount);});

Protractor- ElementFinder returning unexpected values

I am writing a protractor test case to compare the name(s) of the displayed data is same as the searched name.
Even though my test case works fine, I am not able to understand what is happening. Because when i expect the name to compare, it compares as expected, but when i print the elementFinder's(rowData)(i have attached the output screen shot here) value in console.log, it show a huge list of some values which i am not able to understand?
PS: I am a newbie to protractor`
This is the testCase:
it('should show proper data for given last name', function () {
var searchValue='manning';
searchBox.sendKeys(searchValue);
search.click();
element.all(by.binding('row.loanNumber')).count().then(function(value) {
var loanCount = value;
for (var i = 0; i < loanCount; i++) {
var rowData = element.all(by.binding('row.borrowerName')).get(i).getText();
expect(rowData).toMatch(searchValue.toUpperCase());
console.log(rowData,'*****',searchValue.toUpperCase());
}
});
});`
And give me valuable suggestions about my style of code
rowData is a promise (not a value), so when you console.log it, you get the promise object
Protractor patches Jasmine to automatically resolve promises within the expect(), so that's how it knows to resolve the value and compare to the expected result.
If you want to console.log the value, you need to resolve the promise with .then() to get the value.
rowData.then(function(rowDataText) {
console.log(rowDataText);
)}
This is pretty much everyone's first question when they start using protractor. You will want to learn how promises work if you want a good understanding of how to manipulate them.

jayData complex filter evaluation

I am new to jayData and am trying to filter on an entity set. The filter needs to perform an complex evaluation beyond what I saw in the samples.
Here is a working sample of what I am trying to accomplish (the listView line isn't and is just there to show what I plan to do with the data):
function () {
var weekday = moment().isoWeekday()-1;
console.log(weekday);
var de = leagueDB.DailyEvents.toArray(function (events) {
console.log(events);
var filtered = [];
for (var e = 0; e < events.length;e++) {
console.log(events[e]);
console.log(events[e].RecurrenceRule);
var rule = RRule.fromString(events[e].RecurrenceRule);
var ruleOptions = rule.options.byweekday;
var isDay = ruleOptions.indexOf(weekday);
console.log(ruleOptions, isDay);
if(isDay =! -1)
{
filtered.push(events[e]);
}
}
$("#listView").kendoListView({dataSource:filtered});
});
Basically it is just evaluating a recurring rule string to see if the current day meets that criteria, if so add that event to the list for viewing.
But it blows up when I try to do this:
eventListLocal:leagueDB.DailyEvents.filter(function(e){
console.log("The Weekday is:"+viewModel.weekday);
console.log(e);
console.log("The recurrence rule is:"+e.RecurrenceRule);
var rruleOptions = viewModel.rruleOptions(e.RecurrenceRule);
if (rruleOptions !== -1) {
return true;
}
}).asKendoDataSource()
The error that is generating is:
Exception: Unable to resolve type:undefined
The thing is it seems to be occurring on "e" and the console logs like the event is not being passed in. However, I am not seeing a list either. In short I am really confused as to what is going on.
Any help would be appreciated.
Thanks,
You can't write filter expressions such as this.
When you write .filter(...), jaydata will parse your expression and then it will generate filter for underlying provider, for example where for webSql and $filter for oDataProvider.
Both JayData expression parser and the data provider itself should understand your filter.
Your filter is not suitable for this approach, because most of your codes are not familiar for jaydata expression parser and the underlying data provider, for example your console.log etc.
You can simplify your filter, or you should load all your data into an array, and then you can use filter method of array itself, there, you can write any filter you like, and your filter will work. Of course this has performance issue in some scenarios when your data set is large.
Read more on http://jaydata.org/tutorials/entityexpressions-the-heart-of-jaydata

Passing query results in a viewbag

This seems like it should be so easy, but I've tried three or four ways to do it (but to no avail).
I'm just trying to put a query result in a viewbag and display it.
I've tried putting a model object list in a ViewBag:
var mesg = from MSG in lemondb.Messages
where MSG.msg == Membership.GetUser().ToString()
select MSG;
ViewBag.messages = MSG;
And then I try to spit it out in a .cshtml:
var message = (List<LemonTrader.Models.Message>)ViewBag.messages; // <--- fails here because it is a string
foreach ( var MSG in message )
{
#Html.Label(MSG.msg)<br />
}
But it says:
Cannot convert type
'System.Data.Entity.Infrastructure.DbQuery'
to
'System.Collections.Generic.List'
So it seems I'm using using the wrong template. How do I spit out a System.Entity.Infrastructure.DbQuery?
I've also tried passing the results through the Viewbag as a list of strings. (Is that a worse way to do it?)
var mesg = from MSG in lemondb.Messages
where MSG.msg == Membership.GetUser().ToString()
select MSG.msg;
ViewBag.messages = mesg;
And spitting it out as a string list:
foreach (var atext in ViewBag.messages as List<string>) { // gets hung up on foreach here (why???)
#Html.Label( atext )
}
And I get this:
Object reference not set to an
instance of an object.
And it points at the "foreach" keyword.
Does that mean there were no messages? Or what?
I wish there was a tutorial showing how to put queryresults in a ViewBag and how to get them out! I've seen tutorials that return an object.ToList() without respect to any kind of "where" mechanism, but no examples to pull out a few, relevant entries and display them.
Try
ViewBag.messages = MSG.ToList();
Also, System.Data.Entity.Infrastructure.DbQuery implements IEnumerable ( http://msdn.microsoft.com/en-us/library/system.data.entity.infrastructure.dbquery(v=vs.103).aspx ) so this should also work:
var message = (IEnumerable<LemonTrader.Models.Message>)ViewBag.messages;