Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use callback asynchronously

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)
like image 769
Biswadev Avatar asked Apr 20 '18 09:04

Biswadev


People also ask

Can a callback be async?

Simply taking a callback doesn't make a function asynchronous. There are many examples of functions that take a function argument but are not asynchronous. For example there's forEach in Array. It iterates over each item and calls the function once per item.

How do you create asynchronous callback?

The only way to make something asynchronous was to use a host-provided function, such as nextTick (or any of the various operations that completes asynchronously) on NodeJS or setTimeout on browsers.

Is callback function asynchronous or synchronous?

The callback is a function that's accepted as an argument and executed by another function (the higher-order function). There are 2 kinds of callback functions: synchronous and asynchronous. The synchronous callbacks are executed at the same time as the higher-order function that uses the callback.

How are async callbacks implemented?

Different languages have different implementations for asynchronous callbacks, but the principles are the same. The key is to decouple the control flow from the code executed. They correspond to the execution context (like a thread of control with a runtime stack) and the executed task.


1 Answers

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")
like image 199
CertainPerformance Avatar answered Sep 22 '22 23:09

CertainPerformance