I'd like to receive a response (true or false) from a called function to decide if the function should continue or stop. Look at the following code for better understanding:
function function1() {
function2(); // call function2
// after called function (here I need true or false, to decide if the function should stop or continue)
}
function function2() {
if (condition === value) {
// do something, give function1 a response to continue
} else {
// do something, give function1 a response to stop
}
}
Updated:
function function1() {
console.log('call function2');
function2(); // call function2
// after called function (here I need true or false, to decide if the function should stop or continue)
console.log('back from function2');
}
function function2() {
if (condition === false) {
console.log('condition === false');
return;
}
}
You don't need an else on the statement. check to see if your variable is false and if it is it will return if not the rest of your function will run automatically.
function function1() {
function2(); // call function2
// after called function (here I need true or false, to decide if the function should stop or continue)
}
function function2() {
if (condition === false) {
return;
}
}
If function2 is synchronous you can just return:
function function1() {
if(!function2()){
return
}; // call function2
// after called function (here I need true or false, to decide if the function should stop or continue)
}
function function2() {
if (condition === value) {
return true;
} else {
return false;
}
}
If function 2 does something asynchronous and expects a callback (one of the tags in your question) then it may be easier to write a function that will use function2 and returns a promise.
function function1(condition) {
console.log('calling function 2');
function2AsPromise(condition).then(function(
function2Result
) {
if (!function2Result) {
console.log('function 2 result is false');
return;
}
console.log('function 2 result is true');
});
console.log('exiting function 2');
}
function function2(condition, callback) {
setTimeout(function() {
if (condition) {
callback(true);
} else {
callback(false);
}
}, 2000);
}
function function2AsPromise(condition) {
return new Promise(function(resolve) {
function2(condition, resolve);
});
}
function1(false);
const function1 = check => {
if (check === false) {
return;
} else {
console.log("back from function2");
}
};
function1(false) // console.log doesn't run
function1(true) // console.log runs
make sure that you pass in a Boolean value.
Related
I have two simple functions:A function which returns a promise
function showBootbox(){
return new Promise(function (resolve, reject) {
bootbox.confirm('Are you sure ? ',resolve);
});
}
and a function which uses a callback.
function getBootboxValue(callback) {
showBootbox().then(function (result) {
callback(result);
});
}
Now the problem is that i can't await for callback to finished.
if(condition){
getBootboxValue(function(result){
if(result){
//code
}
});
}
console.log('a');
console.log(a) is executing before I got the result of promise. How can I do this without using async/await mechanism ?
Thanks in advance!
If I didn't get it wrong, your idea is to console.log('a') immidiately if the condition is not met and console.log('a') at the end of the callback if the condition is met.
If that is so, one option could be to return the promise of getBootboxValue(callback) when the condition is met and an already fulfilled promise if the condition is not met. You'd then use a callback for that promise that would contain the console.log('a').
function showBootbox() {
return new Promise(function(resolve, reject) {
console.log('Are you sure ? ');
resolve();
});
}
function getBootboxValue(callback) {
return showBootbox().then(function(result) {
callback(result);
});
}
function test(condition) {
var cbk = function(result) {
console.log('Launching callback');
if (result) {
//code
}
},
aux = condition ? getBootboxValue(cbk) : Promise.resolve(null);
aux.then(function() {
console.log('a')
});
}
test(true);
test(false);
Hope it helps.
I think this is what you are after. If you need to conditionally execute an async function and then run some code else run that code anyway you can put the code in a function and call it in either situation:
if(condition){
getBootboxValue(function(result){
if(result){
//code
}
doSomething();
});
} else {
doSomething();
}
function doSomething() {
console.log('a');
}
I'm trying to create a bounce effect on an image after an synchronous AND an asynchronous call but can't figure out how to do it. The problem I'm having now is that I sometimes get both the bounce effect and afterwards isExecuted becomes true because the asynchronous event takes some time.
My code should work like this:
Iterate over each object in myEnum and execute the following
if myCondition1 is equal too myCondition2 set isExecuted = true
if above is not true, call an asynchronous method which evaluates some stuff, if it's true it will set isExecuted = true.
wait for all above is finished, then if isExecuted still is false, bounce the image.
Here's the code:
var isExecuted = false;
myEnum.each()
{
if (myCondition1 == myCondition2) { //Synchronous
isExecuted = true;
return false; //stop the iteration
}
else {
MyAsyncFunction(myCondition2, function(isTrue) { // Asynchronous
if (isTrue) {
isExecuted = true;
return false; //stop the iteration
}
});
}
});
// Execute this ONLY when above code is finished executing
if (isExecuted == false) {
BounceImage();
}
Please note that the async function is not always executed but the bounce check must always be executed if isExecuted is true.
This whole setup won't work as you want because you cannot stop the iteration from the asynchronous callback. Instead you have to process the array (or whatever myEnum is) asynchronously and do something afterwards. I highly recommend to learn about promises.
function process(array, cb) {
var i = 0;
function p(v) {
return new Promise((resolve, reject) => {
try {
// call the callback, passing in the current value and
// a callback to control execution
cb(v, function next(stop, result) {
if (stop) {
// if stop = true, abort the iteration and resolve the passed in value
resolve(result);
} else if (i < array.length) {
// else if there are more elements left, process them
resolve(p(array[i++]));
} else { // else resolve to the passed in value
resolve(result);
}
});
} catch(e) {
reject(e);
}
});
}
// start with the first element
return p(array[0]);
}
process([1,2,3], function(v, next) {
if (v == 2) {
return next(true, v);
}
next();
}).then(result => console.log(result));
Applied to your code it would look something like
process(myEnum, function(v, next) {
if (myCondition1 == myCondition2) {
return next(true, true);
} else {
MyAsyncFunction(myCondition2, function(isTrue) {
if (isTrue) {
return next(true, true);
}
next();
});
}
}).then(function(isExecuted) {
if (!isExecuted) {
BounceImage();
}
});
Of course you can also use an existing library that allows you to do this. There a many different (potentially more elegant) ways to achieve this.
Instead, use callbacks:
function asyncFunction (a, b, c, callback) {
...
callback();
}
asyncFunction(1, 2, 3, function () {
doSomethingOnceDone();
});
This is a very common practice. It's how most async Chrome APIS do it, just to name one thing.
If i am ina function which was called from inside another function, how do I exit out of the main/parent function?
e.g:
function(firstFunction(){
//stuff
secondFunction()
// stuff if second function doesnt exit
}
function secondFunction(){
if( // some stuff here to do checks...){
/***** Exit from this and firstFunction, i.e stop code after this function call from running ****/
}
}
The other answers are obviously correct, but I'd differ slightly and do it this way...
function firstFunction() {
if (secondFunction()) {
// do stuff here
}
}
function secondFunction() {
if (something) {
return false; // exit from here and do not continue execution of firstFunction
}
return true;
}
It's just a difference of opinion in coding styles really, and will have no difference to the end result.
You can return some value to indicate that you want to exit from the firstFunction().
e.g.
function(firstFunction(){
//stuff
rt = secondFunction()
if (rt == false) {
return; // exit out of function
}
// stuff if second function doesnt exit
}
function secondFunction(){
if( // some stuff here to do checks...){
/***** Exit from this and firstFunction, i.e stop code after this function call from running ****/
return false;
}
return true;
}
You cannot directly return control flow 2-steps up the stack. However you could return a value from your inner function which is then handled in the outer. Something like this:
function(firstFunction(){
var result = secondFunction()
if (!result)
return
}
function secondFunction(){
if( /* some stuff here to do checks */ ){
return false;
}
return true;
}
you should do a callback like this:
function firstFunction () {
secondFunction(function () {
// do stuff here if secondFunction is successfull
});
};
function secondFunction (cb) {
if (something) cb();
};
this way you can do asyncronous stuff in secondFunction too like ajax etc.
function MyFunction () {
if (SomeCondition) {
MyInnerFunction(SomeParam);
return;
}
if (SomeOtherCondition) {
MyInnerFunction(SomeOtherParam);
return;
}
if (SomeThirdCondition) {
MyInnerFunction(AnotherParam);
return;
}
function MyInnerFunction(Param) {
// Do some work here
// HERE: I want return from MyFunction
}
}
As you can see, when MyInnerFunction returns, the next statement to execute is the return statement of MyFunction. Is there a way to eliminate all these return statements so that the return from MyFunction executes inside MyInnerFunction?
Thanks.
you could reformat the code so that your if conditions are only modifying the parameters.
Then you just call your method with the correct parameters at the end
function MyFunction () {
var params;
if (SomeCondition)
params = SomeParam;
else if (SomeOtherCondition)
params = SomeOtherParam;
else if (SomeThirdCondition)
params = AnotherParam;
MyInnerFunction(params);
}
When I run the following codes, the alert popup displays undefined. I thought it would return either true or false instead. Please can someone explain how the checkLoginStatus() function excutes. Thanks.
function checkLoginStatus() {
$.get("func.php", {op:'login_status', r:Math.random()}, function(data) {
if (data == "Yes") {
showSalesView();
return true;
} else {
loginView();
return false;
}
});
}
alert(checkLoginStatus());
There's a couple things wrong.
One, you're performing an asynchronous call within the function, so by the time the call has come back, checkLoginStatus has already returned. It essentially looks like this:
function checkLoginStatus() {
$.get("func.php", {
op: 'login_status',
r: Math.random()
}, function(data) {
if (data == "Yes") {
showSalesView();
return true;
} else {
loginView();
return false;
}
});
// return undefined
}
Second, you're returning within the callback of another function, so that return affects the return value of the callback to $.get
You want to use callbacks. So,
function checkLoginStatus(callback) {
$.get("func.php", {
op: 'login_status',
r: Math.random()
}, function(data) {
if (data == "Yes") {
showSalesView();
callback(true);
} else {
loginView();
callback(false);
}
});
}
and then
checkLoginStatus(function(result) {
alert(result);
});
The AJAX call is asynchronous, so the function that you specify as callback will be executed when the response arrives. The code doesn't wait for the response to exit from the checkLoginStatus function.
You can use a callback method to display the result:
function checkLoginStatus(callback) {
$.get("func.php", {op:'login_status', r:Math.random()}, function(data) {
if (data == "Yes") {
showSalesView();
callback(true);
} else {
loginView();
callback(false);
}
});
}
checkLoginStatus(function(status){ alert(status); });
what you are seeing is the undefined (void) return from the .get() function,
notice carefully that .get function call contains another function as the third parameter ( first being the url, second being an anon object) that is the "callback" for the results of the .get function, this is called later when the results have been returned from the server.
The returned bool is being returned by the $.get functions callback, not checkLoginStatus.
function checkLoginStatus() {
$.get("func.php", {op:'login_status', r:Math.random()},
// Start Callback Function
function(data) {
if (data == "Yes") {
showSalesView();
return true;
} else {
loginView();
return false;
}
// End Callback Function
});
}