cvoigt
cvoigt

Reputation: 587

Calling functions asynchronous

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?

Upvotes: 0

Views: 54

Answers (1)

Suman Bogati
Suman Bogati

Reputation: 6349

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.

Upvotes: 2

Related Questions