Is it possible to get data of two files like so using then function using bluebird promise? - bluebird

Is it possible to get data of two files like so using then function using bluebird promise?
fs.readFileAsync('directory/file1.txt')
.then(function(fileData1){
return fs.readFileAsync('directory/file2.txt');
})
.then(function(fileData2){
return console.log(fileData1+fileData2);
})

You can just wrap the first fs.readFileAsync('directory/file1.txt') call in Bluebird.resolve to convert to Bluebird promises, but you won't have the result of the first file in the handler of your second 'then' function.
In your case you can do them both in parallel using Bluebird.all.
Bluebird.all([
fs.readFileAsync('directory/file1.txt')
, fs.readFileAsync('directory/file2.txt')
])
.spread(function(file1, file2) {
console.log(file1 + file2);
})
If you use Bluebird.all remember that it takes an Array.

Related

What is the best options for looping over NodeList?

All looping variants work but which one is the right one to use for the NodeList and what differences are there I need to be aware of?
const els = document.querySelectorAll("div");
for (const el of Array.from(els)) {
//..
};
Array.from(els).forEach((el) => {
//..
});
Array.from(els).map((el) => {
//..
});
For Loop
forEach Loop
It is one of the original ways of iterating over an array.
It is a newer way with lesser code to iterate over an array.
It is faster in performance.
It is slower than the traditional loop in performance.
The break statement can be used to come out from the loop.
The break statement cannot be used because of the callback function
The parameters are the iterator, counter, and incrementor.
The parameters are the iterator, index of item, and array to iterate.
It works with the await keyword.
The await keyword cannot be used due to the callback function. It may lead to incorrect output
As always, the choice between map() and forEach() will depend on your use case. If you plan to change, alternate, or use the data, you should pick map(), because it returns a new array with the transformed data.

How to work with data returned by mysql select query in nodejs

I am working on a discord bot written in nodejs, the bot utilises a mysql database server to store information. The problem I have run into is that I cannot seem to retrieve the data from the database in a neat way, every single thing I try seems to run into some issue or another.
The select query returns an object called RowDataPacket. When googling every single result will reference this solution: Object.values(JSON.parse(JSON.stringify(rows)))
It postulates that I should get the values back, but I dont I get an array back that is as hard to work with as the rowdatapacket object.
This is a snippet of my code:
const kenneledMemberRolesTableName = 'kenneled_member_roles'
const kenneledMemberKey = 'kenneled_member'
const kenneledMemberRoleKey = 'kenneled_member_role_id'
const kenneledStaffMemberKey = 'kenneled_staff_member'
const kenneledDateKey = 'kenneled_date'
const kenneledReturnableRoleKey = 'kenneled_role_can_be_returned'
async function findKenneledMemberRoles(kenneledMemberId) {
let sql = `SELECT CAST(${kenneledMemberRoleKey} AS Char) FROM ${kenneledMemberRolesTableName} WHERE ${kenneledMemberKey} = ${kenneledMemberId}`
let rows = await databaseAccessor.runQuery(sql)
let result = JSON.parse(JSON.stringify(rows)).map(row => {
return row.kenneled_member_role_id
})
return result
}
This seemed to work, until I had to do a type conversion on the value, now the dot notations requires me to reference row.CAST(kenneled_member_role_id AS Char), this cannot work, and I have found no other way to retrieve the data than through dot notation. I swear there must be a better way to work with mysql rowdatapackets but the solution eludes me
I figured out something that works, however I still feel like this is an inelegant solution, I would love to hear from others if I am misunderstanding how to work with mysql code in nodejs, or if this is just a consequence of the library:
let result = JSON.parse(JSON.stringify(rows)).map(row => {
return row[`CAST(${kenneledMemberRoleKey} AS CHAR)`];
})
So what I did is I access the value through brackets instead of dot notation, this seems to work, and at least makes me able to store part of or the whole expression in a constant variable, hiding the ugliness.

Conditional inside es6 .map

project im working on used es6/jsx and the airbnb linter but im having some trouble with the following code: i need to map items and compare it to another id but when i write it like this i get an error on the if statement, which is "parsing error unexpected token".
tried parentheses around the item, brackets after fat arrow, but not sure what the issue is. dont need to add return since it knows to expect it back. trying to find the way to get this working with the correct syntax.
const cartItems = items.map(item => {
if (id === item._id) {
console.log('found', item_id);
}
});
edit:
doing it like that, the .map(item has an error: expected parentheses around arrow function having curly braces.
moving over the => { i get an error: expected to return a value in arrow function
and in the console.log the item_id has a error: item._id is not defined, it should have been defined with the map but seems its not seeing it?
basically need to loop through the items id's and match them against another set of ids, if they match i need to combine the matching ones into a new variable
Ive changed it a bit, for what i need by doing it like this:
if (id === items.map(item => item._id)) {
this.setState({ inCart: true });
}
then just use the state value to conditionally load anything i needed.

How to satisfy the lint rules 'array-callback-return'?

This is my first cut:
const planLimits = {plan1: {condition1: 50, ...}}
function initialisePlanLimits(planLimits) {
const limits = new Map();
Object.keys(planLimits).map((planId) => (
const limitMap = new Map(Object.entries(planLimits[planId]));
limits.set(planId, limitMap);
));
return limits;
}
The linter flags this error: error Expected to return a value in this function array-callback-return
So I changed to this version:
function initialisePlanLimits(planLimits) {
const limits = new Map();
Object.keys(planLimits).map((planId) => (
limits.set(planId, new Map(Object.entries(planLimits[planId])))
));
return limits;
}
It throws another error Unexpected parentheses around single function argument having a body with no curly braces arrow-parens
My questions:
1) I reckon I can fix my first version by sticking in a return null within the curry bracket. But is there a better, more elegant way? A bogus return statement does not make sense in this context
2) Why the second version fails? Isn't it equivalent to the first version?
If I use forEach instead of map, it will not cause the array-callback-return lint error
Object.keys(planLimits).forEach((planId) => (
const limitMap = new Map(Object.entries(planLimits[planId]));
limits.set(planId, limitMap);
));
Well, accepted answer advocates about using 'forEach,' which is true. Please read below explaination from ESLint documentation,
Array has several methods for filtering, mapping, and folding. If we forget to write return statement in a callback of those, it's probably a mistake. If you don't want to use a return or don't need the returned results, consider using .forEach instead.
TLDR: ESLint and Function Return Values
This issue is caused by not returning a value when using map(), see how the results are expected according to the docs...
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array. (Source: MDN WebDocs.)
Demonstration of Issue in JavaScript
With this code sample of JS, which shows a group of elements...
var newarray = [];
array.map( (item, index) => {
newarray.push('<li>' + item + '</li>');
});
I get this error...
Expected to return a value in arrow function array-callback-return
The error goes away if I add a single return to the above function, like so :
var newarray = array.map( (item, index) => {
return '<li>' + item + '</li>';
});
`map()` - So why should I use it?
You can clearly see elsewhere, too, on MDN Docs, that what is returned is, "A new array with each element being the result of the [return value of the] callback function." So, if you are using map(), it's also a very good idea to also use return returnvalue!
map() is a powerful tool. Don't throw that tool away.

Using a function return for parameters of other function (in python)

So, I was wondering if it was possible to use the return information from one function as the parameters for another without using a variable. The function I am trying to use takes two parameters (and self because it's part of a class) and the other function returns two values. The best I can get is:
import ccrlib
authinfo = ccrlib.getauth()
session = ccrlib.CCRSession(authinfo[0], authinfo[1])
Otherwise I would have to run getauth twice:
import ccrlib
session = ccrlib.CCRSession(ccrlib.getauth()[0], ccrlib.getauth()[1])
Which is most obviously less efficient.
You can use star unpacking:
session = ccrlib.CCRSession(*ccrlib.getauth())