Usage of Javascript syntax : method(param1,param2,(something)=>{//some code},param4); - javascript

This method syntax seems to be little strange.
Here is the method declaration. Some normal javascript method implementation.
sendHttpRequest: function (aUri, aUploadData, aContentType, aExisting, aSetupChannelFunc, aFailureFunc, aUseStreamLoader = true) {
//method implementation
}
This is the actual usage. There what does mean by using ()=>{//some statements} as a parameter?
function someFunction(){
this.calendar.sendHttpRequest(requestUri, queryXml, MIME_TEXT_XML, null, (channel) => {
//some statements
return this;
}, () => {
if (this.setA && this.setB) {
//some statements
}
}, false);
//someFunction's statements
}

Related

How to return the value of SweetAlert2 input?

This is the current code I have
function getInput() {
Swal.fire({
input: "text",
}).then((result) => {
if (result) {
return(result.value);
});
}
function main() {
if (condition) {
const test = getInput();
} else {
// do something else
}
}
I know this isn't correct because it returns undefined. I've tried looking for a bunch of solutions but I always get undefined or the promise itself returned, have no idea how I'm supposed to get the value.
What I want to do is somehow return the value of the SweetAlert2 input so that I can use it in other functions.
Edit
I think I got mostly what I had wanted to do. Instead of putting the then handler in getInput(), I put it on test, so then I could put the rest of my code in the handler.
function getInput() {
return Swal.fire({
input: "text",
})
}
function main() {
if (condition) {
const test = getInput();
test.then((result) => {
if (result) {
// do stuff
}
});
} else {
// do something else
}
}
Ideal use case to use a callback as your program is not certain when the value will be returned.
In then handler, callback function will be invoked and input will be passed as an argument.
function getInput(cb) {
Swal.fire({
input: "text",
}).then((result) => {
if (result) {
return cb(result.value);
});
}
}
function main(input) {
console.log(input);
}
getInput(main)

Exported function to pass arguments and a constant to another function

I don't really know how to describe this, but I'll try explain it.
I want to be able to call func1() and func2(), but going through handler() in a module.
I want it in a way where calling module.exported1("foo") will call handler(func1, "foo"), in turn calling func1("foo"). The issue I'm having is that if I export 'exported1' as handler(func1), I can't pass any arguments exported1 was called with (As far as I know). Is there a workaround for this?
NOTE: It is a module, and I need it to be exported without the user needing to provide func1 and func2 to handler().
function func1(args) {
...
}
function func2(args) {
...
}
function handler(func, args) {
return func()
}
module.exports = {
exported1 = handler(func1, ...),
exported2 = handler(func2, ...)
}
Not sure I get why to use this pattern, but I am sure there is more to the code and guess you could do the following:
function func1(args) {
console.info(`func1 ${args}`);
}
function func2(args) {
console.info(`func2 ${args}`);
}
function handler(func, args) {
return func(args);
}
module.exports = {
exported1: (args) => {
return handler(func1, (args));
},
exported2: (args) => {
return handler(func2, (args));
},
};
You just need to export the function:
module.exports = {
exported = handler
}
Or, just:
exports.exported = handler
Now, after import, you can call with parameters:
exported(func1,...)
exported(func2,...)
After reading your edited question, I think you want to do something like this but I'm not pretty sure:
function handler(func) {
// you can replace it with function(args) { instead of arrow function
return (args) => {
return func(args)
}
}
module.exports = {
exported1 = handler(func1),
exported2 = handler(func2)
}
exported1(args)

jsx syntax that confuses me

I saw the next code:
const cardSource = {
beginDrag(props) {
return {
text: props.text
};
}
};
Typically I use {} for jsx block code or to build objects. cardSource makes me feel uneasy. Is beginDrag a member of cardSource? If so, can I use the call: cardSource.beginDrag()?
Is beginDrag a member of cardSource?
Yes. This is equivalent to :
const cardSource = {
beginDrag: function beginDrag(props) {
return {
text: props.text
};
}
};
If so, can I use the call: cardSource.beginDrag()?
Yes.

Passing arguments while running lodash flow asynchronously

Given the code below, how can I pass id to the applySaveAsync function?
var then = _.curry(function (f, thenable) {
return thenable.then(f);
});
var validateAsync = _.flow(
function () { return _(someCondition).showError(ERROR_01).value(); },
then(function () { return _(anotherCondition).showError(ERROR_02).value(); })
);
var save = _.flow(
validateAsync,
then(applySaveAsync),
then(saveCompleted)
);
function applySaveAsync(id) {
// Saving...
}
save(22); // Calling save function with some id.
I can get the id on the validateAsync function, but I cannot return it back since validateAsync should return a promise.
Any way to achieve that?
The simplest choice would be not to use _.flow for the definition of validateAsync.
Since validateAsync does not take parameters nor has a result, you should just change the definition of save to not use _.flow:
function save(id) {
return validateAsync()
.then(function(){ return applySaveAsync(id) })
.then(saveCompleted)
}
We could also change validateAsync to pass through the id:
function validateAsync(id) {
return _(someCondition).showError(ERROR_01).value()
.then(function () { return _(anotherCondition).showError(ERROR_02).value(); })
.then(_.constant(id));
}
and even do that while still using _.flow
var validateAsync = _.flow(
function(id) { return _(someCondition).showError(ERROR_01).value().then(_.constant(id)); },
then(function(id) { return _(anotherCondition).showError(ERROR_02).value().then(_.constant(id)); })
);
but I would advise against that since validateAsync is not supposed to be a function that does takes parameters.
Let's write a wrapper function for such instead to let us do the pass-around in a functional way:
function pass(fn) {
return function(id) {
return fn().then(function() {
return id;
});
}
}
(if you prefer, you can try to compose that from then, _.constant and more)
so that one can write
var save = _.flow(
wrap(validateAsync),
then(applySaveAsync),
then(saveCompleted)
);
I found this package useful for you. In Async cases, you can use this package.
Although flow is one of the best implementations for declarative programming, it doesn't support modern JS programming style.
import { Conductor } from '#puzzleio/conductor';
const conductor = Conductor.createDefault();
const myAsyncWorkflow = conductor
.add(validateAsync)
.if({
check: item => item.isValid === true,
handler: item => console.log('Item is valid')
},
{
// else block
handler: item => console.log('Validation failed')
});
myAsyncWorkflow.run(obj)
.then(() => console.log('Successfully validated'))
.catch(console.error);

How To Refactor If-else Code Segment?

I'm developing win8(metro style) application with Html5-js-jquery.
I have this code segment;
GetBoutiqueDetail: function (boutiqueId, options) {
if (IsUserLogin()) {
//different job A
} else {
ShowLoginPanel(undefined);
}
},
GetProductDetail: function (boutiqueId, productId, options) {
if (IsUserLogin()) {
//different job B
} else {
ShowLoginPanel(undefined);
}
},
AddBasket: function (productId, productVariantId, quantity, options) {
if (IsUserLogin()) {
//different job C
} else {
ShowLoginPanel(undefined);
}
},....
.And ~20 functions should check if user login or not.
I should call functions like similar to "Library.GetBoutiqueDetail();"
So my question is simple, how can I refactor that code to remove these if-else sections ?
Try something like this:
checkLogin: function( action, actionArgs ) {
if( IsLogin ) {
return action.apply(this, actionArgs );
}
ShowLoginPanel();
},
GetBoutiqueDetail: function (boutiqueId, options) {
//different job A
},
GetProductDetail: function (boutiqueId, productId, options) {
//different job B
},
AddBasket: function (productId, productVariantId, quantity, options) {
//different job C
}
How about an object map for this:
var objMap = {
"GetBoutiqueDetail":fnJobA,
"GetProductDetail":fnJobB,
"AddBasket":fnJobC}
....
}
if (loggedIn) {
objMap[task]();
}
else {
doLogin();
}
You could always wrap the common code into a higher-scope function, and have it invoked from the library functions - e.g:
//Higher scope:
function CheckForLogin(executionFunction)
{
if(IsLogin) {
executionFunction();
} else {
ShowLoginPanel(undefined);
}
};
GetBoutiqueDetail: function (boutiqueId, options) {
CheckForLogin(//different job A)
}
Passing in different job 'N' as an anonymous function to CheckForLogin
In Javascript you can return from a function to end it, so f.ex:
GetProductDetail: function (boutiqueId, productId, options) {
if (!IsLogin) return ShowLoginPanel();
// different job...
}
You will still have some repetitive code though. Another option is to define a higher level function. Something like:
var loginOrAction = function() {
if (!IsLogin) return ShowLoginPanel();
var args = [].slice.call(arguments);
Library[args.shift()].apply(Library, args);
}
loginOrAction('GetBoutiqueDetail', boutiqueId, options);
use the ternary operator
(IsLogin) ? jobA() : ShowLoginPanel(undefined)

Categories