It rather depends on the nature of main.add()
. But, by its use of a callback, it's most likely asynchronous. If that's the case, then return
simply won't work well as "asynchronous" means that the code doesn't wait for result
to be available.
You should give a read through "How to return the response from an AJAX call?." Though it uses Ajax as an example, it includes a very thorough explanation of asynchronous programming and available options of control flow.
You'll need to define squre()
to accept a callback of its own and adjust the calling code to supply one:
function squre(val, callback) {
main.add(val, function (result) {
console.log("squre = " + result);
callback(result);
});
});
squre(10, function (result) {
console.log(result);
});
Though, on the chance that main.add()
is actually synchronous, you'll want to move the return
statement. They can only apply to the function
they're directly within, which would be the anonymous function
rather than spure()
.
function squre(val) {
var answer;
main.add(val, function (result) {
console.log("squre = " + result);
answer = result;
});
return answer;
}