1

I'm trying to do some calculation asynchronously and get the result from the calculation in the callback.

function customWithCallBack(callback) {
 //Complex logic calculation that takes time.
   callback();
}

function actualCallBack() {
 console.log("This is callback called after certain event");
}


console.log("First");
customWithCallBack(actualCallBack);
console.log("Second");
//Required Output
First
Second
This is callback called after certain event.


//Actual Output
First
This is callback called after certain event
Second

How can I achieve the required output? That is first "First is printed". Then, "Second". And at last after the completion of complex logic callback is called to print "This is callback called after certain event". Is it possible to do it for complex calculations except network req and i/o operations?

xerox007
  • 54
  • 1
  • 9
  • This is quite a similar question to this link: https://stackoverflow.com/questions/9516900/how-can-i-create-an-asynchronous-function-in-javascript – Geono Jun 21 '17 at 07:50

3 Answers3

1

function customWithCallBack(callback) {
 //Complex logic calculation that takes time.
     setTimeout(function(){ callback(); }, 100);
   
}

function actualCallBack() {
 console.log("This is callback called after certain event");
}


console.log("First");
customWithCallBack(actualCallBack);
console.log("Second");
Gaurav joshi
  • 1,743
  • 1
  • 14
  • 28
0

So you want to end the current callstack, then start a new callstack with your callback. This can be achieved through pushing callback onto the qeue, the qeue contains all triggered event handlers and timers and it starts new callstacks one after another. So you can do:

setTimeout(callback,0,"param1","param2");

So callback is executed after the current callstack ends.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

I was a little inspired by this question, because I hit a similar problem some time ago once I've tried to compute large array. It's a combination of solution that uses setTimeout with chunking operation (so that execution will not block entire thread). Here you can see a package created: https://www.npmjs.com/package/chunked-call