4

Hello Everyone hope you all doing great ,

this is my code , function with name and callback taking the name to callback function to make return the name and console.log it

if i

function doSomething(name,callback) {
    callback(name);
}

function foo(n) {
    return n;
}

var val = doSomething("TEST",foo);
console.log(val);

i got undefined .

if i

function doSomething(name,callback) {
    callback(name);
}

function foo(n) {
    console.log(n);
}

var val = doSomething("TEST",foo);

that works fine and console.log the TEST name .

So why the return not working ?

thanks

4
  • It's as it says. doSomething doesn't return anything in either code (but if you console.log the n variable while the n variable is in scope, it'll be logged) Did you mean to return doSomething()? Commented Jul 30, 2018 at 22:23
  • 1
    return callback(name); Commented Jul 30, 2018 at 22:24
  • I want the foo function to be return n; Commented Jul 30, 2018 at 22:28
  • Yes, let foo return n and make doSometing return callback(name) Commented Jul 30, 2018 at 22:30

4 Answers 4

5

Your doSomething() function doesn't return anything, which means an assignment using it will be undefined. But, that's not really the problem here.

The underlying problem is that you seem to be mixing two different data processing patterns here: if you're writing purely synchronous code, then use returning functions (which immediately return some value). If you need asynchronous code, then use a callback (which will "eventually" do something). Mixing those two patterns is a recipe for problems and frustration:

Either:

  1. don't name your function a "callback", and have it return its processed value, or
  2. make the callback responsible for doing whatever it is you were going to do with val.

Case 1:

function doSomething(data, processor) {
  return processor(data);
}

function passThrough(v) { return v; }

var val = doSomething("test", passThrough);
// immediately use "val" here in for whatever thing you need to do.

Case 2:

function doSomething(data, callback) {
  // _eventually_ a callback happens - for instance, this
  // function pulls some data from a database, which is one
  // of those inherently asynchronous tasks. Let's fake that
  // with a timeout for demonstration purposes:
  setTimemout(() => callback(data), 500);
}

function handleData(val) {
  // use "val" here in for whatever thing you need to do. Eventually.
}

doSomething("test", handleData);

And if you want to go with case 2, you really want to have a look at "Promises" and async/await in modern Javascript, which are highly improved approaches based on the idea of "calling back once there is something to call back about".

2021 edit: a third option since original writing this answer is to use the async/await pattern, which is syntactic sugar around Promises.

Case 3:

async function doSomething(input) {
  // we're still _eventually_ returning something,
  // but we're now exploiting `async` to wrap a promise,
  // which lets us write normal-looking code, even if what
  // we're really doing is returning a Promise object,
  // with the "await" keyword auto-unpacking that for us.
  return someModernAsyncAPI.getThing(input);
}

function handleData(val) {
  // ...
}

async function run() {
  const data = await doSomething("test");
  handleData(data);
}

run();
Sign up to request clarification or add additional context in comments.

4 Comments

I can still recommend looking at modern JS's way of writing asynchronous code - even if your code "has no reason to be async", JS runs in a single thread, and anything that takes a long time will block the thread, including any event handlers, so you generally always want to write async code, to make sure there are plenty of points in your code where the task scheduler can briefly hand control over other things that also need to run.
Ok , i just want to use XMLHttpRequest with call function , the call function will have the responseText
You probably don't want to use that, since it's a rather old mechanism, and requires effectively outdated JS methodology. You want to use the modern Fetch API, instead, which is a nicely explicit async, modern JS way to get remote content. See developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
I just did that favorite products , if user clicked on the image of fav , called the xmlhttprequest and inserted on DataB ,
2
function doSomething(name,callback) {
callback(name);
}

function foo(n) {
   console.log(n);
   return n;
}

var val = doSomething("TEST",foo);

Take a look at above code. When you call doSomething, which internally executes foo it prints on the console because thats what console.log is for. However, after this statement it returns n as well which then is received in doSomething. But its not being returned. To put it simply, what you are mainly doing is

function doSomething(name,callback) {
    const returnValue = callback(name);
}

If you call the above method, it will return undefined. To make it return correct value, you have to call "return returnValue". Similary you have to say return callback(name)

Hope this helps.

Happy Learning

Comments

0

Inorder to assign the returning value/object of a function(in this case doSomething, it should have a return statement. Else the function returns nothing, so when you assign that to val, it is still undefined.

So you modify your code like this:

function doSomething(name,callback) {
    return callback(name);
}
function foo(n) {
    return n;
}
var val = doSomething("TEST",foo);
console.log(val);

Comments

0

undefined is implicitly returned if you don't have a return in your function.

when you call var val = doSomething("TEST",foo), you are aligning the return value of doSomething to val, which is undefined.

function doSomething(name,callback) {
  return callback(name);
}

function foo(n) {
  return n;
}

var val = doSomething("TEST",foo);
console.log(val);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.