I have this validate function component how I can use It to return callback funcion?
the first file only for check validity
export function checkValidity(value, rules, shouldValidat) {
let isValid = true;
return isValid;
}
the second file caller
import { checkValidity } from "../UI/CheckValidity";
let res = checkValidity(vlaue, validationRules, shouldValidat);
callback = () =>{
alert("call back function is done");
}
how I can call the callback function from the first file using react js?
You need to have a callback in checkValidity function.
So you need to add callback as argument in checkValidity(value, rules, shouldValidat, callback) and then simply do:
export function checkValidity(value, rules, shouldValidat, callback) {
let isValid = true;
/*do your validation here and if it's okay then call callback*/
callback();
return isValid;
}
You should write a function which is like ;
callback(email) {
const re = ..... => it should be validation rule
if(re.test) {
return email;
}
return false;
and when you call function in other function you should give your email or other params for function param .
Two callback examples:
Callback when something is true callback(isValid)
Callback to deal with false (if needed) errorcallback(isValid)
export const checkValidity = (value, rules, shouldValidate, callback, errorcallback) => {
let isValid = true; // hardcoded
isValid ? callback(isValid) : errorcallback(isValid)
return isValid;
}
How to invoke
Pass your functions as arguments 4 & 5, in this case, callback and errorcallback
val denotes a parameter passed back from the callback. in our example above were passing isValid which we are now calling val from where checkValidity() is invoked.
import { checkValidity } from "../UI/CheckValidity";
let res = checkValidity(value, validationRules, shouldValidate);
checkValidity(
value,
rules,
shouldValidate,
(val) => {console.log('callback() if true!! ' + val )},
(val) => {console.log('errorcallback() if false!!' + val}
)
Related
Hello I'm learning about Javascript Callback Function, but I don't know how to set a default value to callback function.
let mul = (num1,num2) =>{
return num1*num2;
}
let cal = (num1,num2,cb) =>{
console.log(`The Answer is ${cb(num1,num2)}`)
}
cal(3,2,mul);
Here the code I tried to set a default value to callback function.
let sum = (num1,num2) =>{
return num1+num2;
}
let mul = (num1 = 3,num2 = 2) =>{
return num1*num2;
}
let cal = (num1,num2,cb) =>{
console.log(`The Answer is ${cb(num1,num2)}`)
}
cal(mul);
Instead of cal(numberone,numbertwo,mul);. Can I only call a function like this cal(mul);.
Edit
let testmul = (num1 = 3,num2 = 2) =>{
let result = num1*num2;
console.log(`${result}`);
}
testmul();
This is what I would like to do. If I doesn't put a number in function. The function will have a default value. But this time I want to try it with a Callback function.
The answers to your question read more: https://nodejs.org/en/knowledge/javascript-conventions/how-to-create-default-parameters-for-functions/
You have to check if the last parameter is undefined and then manually fix all the other parameters before continuing in the code. This case is also valid for modern JavaScript(ES6/ES2015). The example shows you how to do that:
const example = function (param1, optParam, callback) {
if (callback === undefined) {
// only two parameters were passed, so the callback is actually in `optParam`
callback = optParam;
//give `optParam` a default value
optParam = "and a default parameter";
}
callback(param1, optParam);
}
example("This is a necessary parameter", console.log);
example("This is a necessary parameter", "and an optional parameter", console.log);
let DefaultCallback = (args) => {
... do stuff
}
then you can do like this:
function myFunc(param1, param2, callback = DefaultCallback){
return param1;
callback();
}
then if you don't provide a callback like myFunc(2) as you said, it will have the default values of the function defaultCallback and it works for other variables as well, if you want to define default function parameters
I have a component in project which accepts a function with callback param. On change of this component this function calls inside. But here is problem, we get some data asynchronously on every change with async await function and after we get some data we do callback. So, on second change, I can see callback call with old data. Standard debounce doesn't work here because of async.
Here is my fast solution with closure:
function doOnlyLastFunction(fnc) {
let id = 0;
const isLast = (currentId) => () => currentId === id;
return (...args) => {
id++;
fnc.call(this, ...args, isLast);
};
}
in runtime shortly:
let closure = null;
function handler(data, cb) {
if (!closure) {
closure = doOnlyLastFunction(async (data, cb, isLast) => {
//await some promises
if (isLast()) {
cb(result); //cb with data
}
});
}
closure(data, cb);
}
I this this is bad solution and I can't change logic on the top level. Is there a way to optimize this logic?
I would suggest moving the isLast() check inside the callback itself that your fnc is calling:
function doOnlyLastFunction(fn) {
let id = 0;
return function(...args) {
const currentId = ++id;
const cb = args.pop();
fn.call(this, ...args, function(...results) {
if (currentId === id)
cb(...results);
});
};
}
Also you don't need to lazily initialise your closure variable from inside handler. Just go for
const handler = doOnlyLastFunction(async (data, cb) => {
//await some promises
cb(result); //cb with data
});
I've created a working recursive for loop, but it only works if my callback has no arguments. I've tried callback(arguments) and callback(...arguments).
Thanks for any help you can provide!
function loopFunc (numOfSteps, callback) {
let i = 0;
if (i >= numOfSteps) {
let i = 0
return
}
callback()
loopFunc(numOfSteps - 1, callback)`enter code here`
}
It works if the callback takes no arguments:
function noArgsHello() {
console.log('hello')
}
const thisWorks = loopFunc(3, noArgsHello);
thisWorks()
It doesn't work if the callback takes an argument:
function sayHello (input) {
console.log(input)
}
const thisDoesntWork = loopFunc(3, sayHello('hello');
thisDoesntWork()
In this way:
const thisDoesntWork = loopFunc(3, sayHello('hello');
You are not passing a callback anymore, but you are executing the sayHello function and passing the returned value of that function to the loopFunc.
What you can do in these cases, is to use the bind method of functions for passing the function with arguments:
const thisDoesntWork = loopFunc(3, sayHello.bind(sayHello, 'hello'));
Or you can pass directly a function which executes your sayHello so that the argument is still a function and it will be used as callback inside your loopFunc:
const thisDoesntWork = loopFunc(3, () => sayHello('hello'));
You almost there! It depends what is your goal here, you can use either option:
function loopFunc (numOfSteps, callback) {
let i = 0;
if (i >= numOfSteps) {
let i = 0
return
}
callback(numOfSteps)
loopFunc(numOfSteps - 1, callback);
}
function printExtraStuff(greeting) {
return (val) => { console.log('greeting ', val)}
}
function printSteps(num) {
console.log(num);
}
var test1 = function() { loopFunc(3, printExtraStuff('hi there') )};
test1()
var test2 = function() { loopFunc(3, printSteps )};
test2()
You need to use an anonymous function if you want to pass parameters in an argument -based function (callback is an argument). Your code should instead be like this:
function sayHello(input) {
console.log(input)
}
const works = () => sayHello('hello');
works();
I want to write some callback functions without parameters.
can anyone tell me below code is correct in typescript or javascript?
myfunction(completeCallBack, failCallBack) {
if (some_condition) {
completeCallBack;
}else {
failCallBack;
}
}
It should be:
function myfunction(completeCallBack, failCallBack) {
if (some_condition) {
completeCallBack();
} else {
failCallBack();
}
}
What you were missing is: ().
If you don't include that then the function won't be executed.
For example:
function fn(): number {
return 10;
}
let a = fn; // typeof a is () => number
let b = fn(); // typeof b is number
Edit
If your function expects two functions with no args then it shouldn't be passed functions who expects args.
You can use typescript to check for that:
type NoParamsCallback = () => void;
function myfunction(completeCallBack: NoParamsCallback, failCallBack: NoParamsCallback) {
if (some_condition) {
completeCallBack();
} else {
failCallBack();
}
}
Then, if you have a function with args but you'd like to pass it anyhow, then you can use the Function.prototype.bind function:
function logNumber(num: number): void {
console.log(`this is the number: ${ num }`);
}
myfunction(logNumber.bind(10), () => {});
Typescript is a superset of javascript. So if it's correct in javascript it sure is correct in typescript;
myfunction is not defined as a function. It's not valid in javascript. It would be valid in typescript if it would pe part of a class.
your code does nothing except evaluating some_condition. It should either call the callbacks or return them.
This is how I think it would be correct:
function myfunction(completeCallBack, failCallBack) {
if (some_condition) {
completeCallBack();
}else {
failCallBack();
}
}
In my case I have one repository like this from temphire (breeze)
define(['durandal/system'], function (system) {
var Repository = (function () {
var repository = function (entityManagerProvider, entityTypeName, resourceName, fetchStrategy) {
.........
this.find = function (predicate) {
var query = breeze.EntityQuery
.from(resourceName)
.where(predicate);
return executeQuery(query);
};
function executeQuery(query) {
return entityManagerProvider.manager()
.executeQuery(query.using(fetchStrategy || breeze.FetchStrategy.FromServer))
.then(function (data) { return data.results; });
}
................
};
return repository;
})();
return {
create: create,
getCtor: Repository
};
function create(entityManagerProvider, entityTypeName, resourceName, fetchStrategy) {
return new Repository(entityManagerProvider, entityTypeName, resourceName, fetchStrategy);
}
});
NOW
HOW CAN DO LIKE SOME THIS
repository.query(predicate).execute();
function query(predicate) {
return query = breeze.EntityQuery
.from(resourceName)
.where(predicate);
};
function executeQuery(query) {
return entityManagerProvider.manager().executeQuery(query.using(fetchStrategy || breeze.FetchStrategy.FromServer)).then(function(data) {
return data.results;
});
}
function execute() -- >
return executeQuery
the first action return query and after to execute
many thanks
I think the problem with what you are trying is that return terminates execution. If you want to do something as well as return in that function, then you need to do it before you return.
If, on the other hand, you really need to return the value and then execute something, then you should have the method that calls the function expecting the return, call the function to get the return value, and then have that calling function execute the thing you want executed. If that execution needs some data from the function that returns the value, then return that information with the value returned, and pass it into the function that does the execution.
Use
executeQueryLocally // This is syn
instead of
executeQuery // This is async
executeQuery sync