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)
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.
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.
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.
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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With