1

Sometimes in nodejs I have to make a request to other host. My function have to wait until the response of this request is completed but usually they comes to next line without any waiting for the finish. To simplify problem, I make a simple snipp code and I want to know how to get data out from this function

function testCallback(){
    var _appData;
    setTimeout(function(){
        var a = 100;
        getData(a);
    }, 200);
    function getData(data){
        _appData = data;
    }
    return _appData;
}


console.log('testCallback: ', testCallback());

console.log send out undefined, I want to know with this function how to get result is 100

1 Answer 1

3

Basically setTimeout is asynchronous, so the code keeps going, your code it becomes, virtually like this:

function testCallback(){
    var _appData;

    return _appData;
}

Which, yes, it is undefined, because you do not set anything.

What you have to do is use a callback in your function, so when the long task (setTimeout) is finished you return the data.

Something like this:

function testCallback(cb){
    setTimeout(function(){
        var a = 100;
        getData(a);
    }, 200);
    function getData(data){
        cb(null, data);
    }
}

and when calling it you have to pass a function as an argument (callback standard has 2 parameters, (err, value).)

testCallback(function(err, value) { console.log(value); });
Sign up to request clarification or add additional context in comments.

2 Comments

But in case I need a return data, I don't want to let other function handle the result, What should I do..?? @DevAlien
If you want a return data, you should NOT do anything which is asynchronous. Node.JS works in a single thread, so it can do one thing at the time. if you spend a lot of time doing one thing, you would block everything else. So when you do an HTTP call the call is done from another process, and when it is finished it will come back to you via a callback. if you are at the beginning you have to think a bit differently than PHP or other languages. I suggest you to take a look at Promises as well, they are pretty cool once you understand how they work.

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.