0

I want to initiate a Database request, which takes several time and responses with an Integer (42). The setTimeout in dbRequest() is representative for this request.

The responded integer should be incremented by 1 in the function initRequest. Therefore initRequest should return 43.

var dbRequest = function () {

  setTimeout(function(){
    console.log('Hello World! => 42');
    return 42;
  }, 5000);

};

var initRequest = function (cb){
  var test = cb() + 1;
  console.log('Incremented Value: ' + test);
  return test;
};

initRequest(dbRequest);

Unfortunately var test = cb() + 1; is not waiting for the setTimeout and calculates with NaN. The output:

Incremented Value: NaN
// 5 sec delay
Hello World! => 42

How can I make this function asynchronous, so that initRequest waits for dbRequest response?

cookie monster
  • 10,671
  • 4
  • 31
  • 45
cvoigt
  • 517
  • 5
  • 16
  • 1
    You seem to have things backwards. The function _is_ asynchronous, that means that it doesn't wait. – Barmar Apr 19 '14 at 14:18
  • 1
    Anything that depends on the result of an asynchronous action has to be done in its callback function. Javascript is single-threaded, it can't stay in the original function and also execute the asynchronous call at the same time. – Barmar Apr 19 '14 at 14:19
  • Basically the same issue has here: http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call That question deals with `AJAX` requests instead of `setTimeout`, but it's the same asynchronous issue – cookie monster Apr 19 '14 at 14:23
  • why dont you call the function after 5 seconds on which you will passed 42, and do some action(increment) with this? – Suman Bogati Apr 19 '14 at 14:24

1 Answers1

2

Exactly don't know about your case but to get the desire result you could do something like this.

var dbRequest = function (callback) {
    setTimeout(function(){
        console.log('Hello World! => 42');
        callback(42);
    }, 5000);
};

function initRequest(val){
    var test = val + 1;
    console.log('Incremented Value: ' + test);
}

 dbRequest(initRequest);

Call the callback function after particular time, and pass the value with this invoked function for desire action.

Suman Bogati
  • 6,289
  • 1
  • 23
  • 34