Promise chain/general code convention/style [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
There is some promise convention best practice which I can use as reference.
I mean something like when you write then you can do it like this
step1().then(step2()).then(retur ...step3())
.catch(function(err) {
console.log(err)
;});
but I think the more readable way is like this
step1()
.then(function() {
return step2();
}).then(function() {
return step3()
}).catch(function(err) {
log(err);
});
There is some official recommendation how to its better to write it in term of readability etc...

Creating intermediate closures is of no benefit if you already have methods ready to hook up.
Your two examples are also doing entirely different things. Your first example should look like this.
step1()
.then(step2)
.then(step3)
.catch(function(err) {
console.log(err)
;});
I don't think there's anything wrong with that. This is also gonna make your stack traces more readable as well.
This is, because, in this example, you have a bunch of intermediate anonymous functions.
As such the stack trace is gonna be containing references to those anonymous functions, while they serve no value.
step1()
.then(function(val) {
return step2(val);
}).then(function(val) {
return step3(val)
}).catch(function(err) {
log(err);
});
In order to prevent the anonymous clutter, you would want to name all your anonymous methods like so.
step1()
.then(function _step2(val) {
return step2(val);
}).then(function _step3(val) {
return step3(val)
}).catch(function(err) {
log(err);
});
I'm prefixing them with an underscore as they can't have the same name as the actual method we are calling off course.
This is a bunch of duplication and it doesn't make much sense because the _step2 and step2 functions are entirely identical.
Also note that in your preferred example you are not passing the parameters correctly, I have added that logic above as well, which as you can see, further increases the noise.

Related

Discord bot I made with node.js is saying "ReferenceError: data is not defined" [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have a discord bot and am trying to disconnect everyone who deafens themselves. I looked it up on the discord.js wiki thing and it looks like Discord.WidgetMember(client, data) is the way to go about it.
Before my code looked like this
client.on('voiceStateUpdate', (oldMember, newMember) => {
const newState = new Discord.WidgetMember.selfDeaf(client, data);
if (newState = true) {
newState.kick();
}
});
That didn't work because it didn't recognize .setDeaf.
So I changed it to this.
client.on('voiceStateUpdate', (oldMember, newMember) => {
const newState = new Discord.WidgetMember(client, data);
if (newState.selfDeaf = true) {
newState.kick();
}
});
That give's me this.
const newState = new Discord.WidgetMember(client, data);
^
ReferenceError: data is not defined
I didn't think I had to define data since it's in the parenthesis. I can just barely get by with this code because I'm super new to it. What do I do to fix it?
The reason why your code didn't work is as #PatrickEvans mentioned in their comment:
That is a function call not a function definition. You are trying to pass information to the function so the variables you use have to exist, check the documentation and see what data it is expected to hold and pass that in.
You were calling a class constructor and you must (unless it has no arguments or they are optional) provide the constructor with data it needs to construct the object with. So the variable data has to be defined somewhere.
Also the other thing that #PatrickEvans pointed out was that you used an assignment operator (=) instead of comparison operator (== or ===). Here (newState.selfDeaf = true), you want to compare the property .selfDeaf with the value of true, not assign it.
You can access the .selfDeaf property directly on the newMember object, which is an instance of GuildMember or VoiceState, depends on the discord.js version you are using. There is no need for Discord.WidgetMember(client, data) at all.
For reference see here: GuildMember.selfDeaf or VoiceState.selfDeaf.
You are probably looking for something like this:
client.on("voiceStateUpdate", (oldMember, newMember) => {
if (newMember.selfDeaf) {
newMember.kick();
}
});
I didn't think I had to define data since it's in the parenthesis.
You might be thinking of incoming arguments in a function, rather than passing arguments to a function. In this case the error is telling you that data isn't defined when you try to execute new Discord.WidgetMember(client, data); The Discord documentation should tell you what you need to pass for this argument.

Jest testing a function with no return [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am in the process of unit testing a function using Jest that merely passes on its parameters to another function by calling it and has no return.
I have googled and tried a bunch of suggested mock implementations, but can't seem to get it to work.
Imported File:
export const firstFunc = (dataObj) => {
secondFunc('anything', dataObj)
}
export const secondFunc = (str, dataObj) => {
// Does something with the dataObj but also doesn't return anything.
}
Essentially what I want to test for is that firstFunc calls secondFunc, but am not able to get it to work.
Thank you in advance. Also, open to suggestions for any other tests that I could run in this situation.
As far as I understood your problem, you could have two solutions.
Firstly, add return value after calling function, and export it to tests.
Secondly, you could use sinon js with jest.
Spying on an imported function that calls another function in Jest

Node js right way to code (scope) [duplicate]

This question already has answers here:
How to avoid long nesting of asynchronous functions in Node.js
(23 answers)
Closed 6 years ago.
I'm new in js. In my project I'm using mysql and node js.
Somewhere in controller I need to get some data from differnet models. In php it looks like
function some() {
$user = $user->getOne($id);
$photos = $photos->getOne($user->id);
$posts = $post($user->id, $photo->uid)
}
and I have all this variables in one scope
in node js result of model is async, so it's look like nestings callbacks.
Short example
UserModel.findbyid(result.user_id, function (err, user_data) {
PhotoModel.GetVoteCount(user_data.id, result.id, function (res_count) {
PhotoModel.getWinners(function (err, winners_ar) {
PhotoModel.getweekusers(1, function (result_week) {
response.render('one.twig', {
view_user: request.user,
image: result,
p_user: user_data,
count: res_count,
winners: winners_ar,
week_users: result_week['photos']
});
});
})
});
});
so I have nested callbacks, I feel it's not right way to code, can you explain best practices?
You have two options :
Use async module (async)
Use a library which returns promises (like promise-mysql).
You can take a look at async module
This simplifies what you call "callback hell" through some functions that helps create flows in async code.
Specifically to your case - async.waterfall will do the trick
Use promises,or libraries that will help you use promises.

How should I split up my js-files to be easy to maintain? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
How would I go about when trying to separate javascript in this manner:
This is my issue:
I have a huge js-file and in this file I have functions that is used for a products-filter. I want to use these "product-filter-functions" at several locations, but I don't want to include a huge js-file.
I would like something like:
huge.js // merely everything that has something to do with products
productfilter.js // inclusion of productfilter-functions */
and when I only want to use product-filter function I obviosly include productfilter.js only.
productfilter.js would have functions like these:
function getSelectedGender() {
...
}
function getSelectedColors() {
....
}
function getSelectedBrandId() {
....
}
If I have a function with the same name in both huge.js and productfilter.js I wouldn't know which of these function would be triggered. (I tried that and it seemed kind of random)
I could of course write new functions (with the same type of functionality) depending on which part of the site I am, but I think that would be poor design and very hard to maintain.
I'm looking for pointers here..
You could try namespacing the JS so that you can keep your function names, e.g.:
huge.functionName()
product.functionName()
instead of
functionName()
functionName()
I'm a fan of RequireJS for developing modules in a tidy manner with well-established dependencies. During building/optimizing the final distribution JS file (if chosen), only the required/requested modules will be included. So code can focus on dependencies and logical grouping, while the build tool includes the relevant modules. Larger or external modules (eg. jQuery) can also be kept external and sourced via manually script includes or loaded via a separate asynchronous "AMD" fetch.
However, even without RequireJS/AMD, modules can be used to keep JavaScript code tidy in separate namespaces. I refer to the "UMD" patterns, adapted to current need. Take this "AMD Web Global" pattern with a jQuery dependency, for instance:
(function (root, factory) {
// The if-branch can be eliminated if /never/ using RequireJS/AMD,
// but leaving it in keeps this pattern compatible with such loaders.
if (typeof define === 'function' && define.amd) {
define(['jQuery'], function (jQuery) {
return (root.foo = factory(jQuery));
});
} else {
root.foo = factory(root.jQuery);
}
}(this, function ($) {
function bar() {
// ...
}
return {
bar: bar
};
}));
Later on the created "namespace" can be used:
foo.bar()
This pattern works with/without AMD (eg. RequireJS) and will also work after combining, if such is chosen. If tool-based combining is not done, then the standard multiple script includes can be used to load the dependencies (a downside is that dependency order must be handled manually).
An added benefit of using such module patterns is it is trivial to change to a context-correct factory builder:
// In the module, exported as window.OptionManager using the above pattern
}(this, function ($) {
function OptionManager (form) {
this.getSelectedGender = function () {
return $(form).find(".gender").val();
};
}
return OptionManager;
}));
And usage:
var options = new OptionManager($("#optionForm"));
options.getSelectedGender();
With the clean distinction of code it is trivial to later combine the different modules, maintaining dependencies, as deemed appropriate - separate files, single monolithic file, several combined files - while the code-base is kept maintainable.

Revealing module implicity calling an internal function - is this a "smell" [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
I'm trying to improve my javascript and have been using the revealing module pattern to good effect but I noticed that code in the module not in a function or the return is executed on creation have utilised this, such as:
var MyModule = function ($) {
setUp();
function setUp() {
// execute code to be run when module created
}
function doStuff() {
}
return {
doStuff: doStuff
}
}
I can see this is creating a form of constructor for the function which relies on it being called by var myModule = new MyModule(jQuery).
Any feedback on the rights or wrongs of this appreciated.

Categories

Resources