5

console.log("before")

function g(p,callback){
    callback('1')
}

g(1,(re)=>{
    console.log(re);
})

console.log("after")

The result is before 1 after. How to make the function call async means the result should be before after 1 without setTimeout function

The usecase is like

I have one api call inside a function and sending response after the this function call.But because this function is called synchronously sending response is delayed.So i want to send response before api call

console.log("before callback")

apiRes.url = [url];
apimanager.callfunc(requestBody, apiRes,(err,success)=>{
    console.log("success ",success)
    console.log("inside callback");
});

console.log("after callback")

return response.json(someresponse)
TwiN
  • 3,554
  • 1
  • 20
  • 31
Biswadev
  • 1,456
  • 11
  • 24
  • use promises instead – Lawrence Cherone Apr 20 '18 at 09:35
  • What is the usecase of that? Or are you just researching Javascript? – vothaison Apr 20 '18 at 09:35
  • 1
    I have one api call inside a function and sending response after the this function call.But because this function is called synchronously sending response is delayed.So i want to send response before api call console.log("before callback") apiRes.url = [url]; apimanager.callfunc(requestBody, apiRes,(err,success)=>{ console.log("success ",success) console.log("inside callback"); }); console.log("after callback") return response.json(someresponse) – Biswadev Apr 20 '18 at 09:44
  • No..its printing beforecallback insidecallback aftercallback..the similar code snippet i shared..i need before after inside.. – Biswadev Apr 20 '18 at 09:55
  • 2
    This sounds like an X/Y problem. At the basic level, i'd consider closing this as a duplicate of "Make a synchronous function asynchronous", but i don't think that's actually going to solve the problem you are facing. Care to expand a bit on what's actually going on in your real code? – Kevin B Apr 20 '18 at 20:16

3 Answers3

4

You could use Promise.resolve():

console.log("before")

function g(p, callback) {
  callback('1')
}

g(1, (re) => {
  Promise.resolve().then(() => {
    console.log(re);
  });
})

console.log("after")
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

You could still use setTimeout nicely, there is nothing wrong with it if you want to schedule your callback to "next tick", just don't use interval param for this, callback will be called as soon as needed asynchronously:

console.log("before")

function g(p, callback) {
  setTimeout(function () { callback('1') })
}

g(1, (re) => {
  console.log(re);
})

console.log("after")
dfsq
  • 191,768
  • 25
  • 236
  • 258
  • I have more than 100 function calls and similar situation..i cannot write setTimeout wrapper for every functioncall..It will increase number of line of codes and ll make unreadable – Biswadev Apr 20 '18 at 09:57
  • @BittuS sounds like you have a problem writing [DRY](https://en.wikipedia.org/wiki/Don't_repeat_yourself) code. That doesn't invalidate this approach. – Patrick Roberts Apr 20 '18 at 10:05
  • @BittuS I don't know what is your problem exactly and why you need to enforce asynchronosity. Your code should be fine as long as it conforms to API of you functions, i.e. uses callback functions. It doesn't matter wether it's sync or async. But in any case wether you use Promises or setTimeout, you will need those extra lines, and you don't have other options really. – dfsq Apr 20 '18 at 10:37
0

Using a call back function like g() for async functions would work a little bit like this.

Firstly we need the function

function g (p,callback){
 callback(p)
};

Awesome. Now lets call in the async function using it

fs.readFile('hello.txt','utf8',function(err,data){//readFile is async
  if(err)throw Error;

  g(data, console.log)//use our callback
});

Tadaa! g will use console.log with the parameters data. If this works, please mark as answer.

More info on here

skpdm
  • 1,378
  • 2
  • 15
  • 31