Interprocess Communication (IPC) · Asynchronous Callbacks · Practice Question
Implement an Asynchronous Callback
Question
What is an asynchronous callback, and how would you implement one?
Solution
On the server, define a function g that uses .z.w (the handle of whoever is currently calling in) to send a result back to the caller asynchronously:
\p 5001
g:{[data;callbackFunction] neg[.z.w](callbackFunction;data+1)}On the client, define the callback function f, and call g on the server asynchronously, passing `f as the name of the callback to invoke:
\p 5002
f:{[x] show x}
h:hopen 5001
neg[h](`g;3;`f)A moment later, the client prints the callback's result:
4Explanation
An async callback lets the client fire a request and move on, while the server sends the result back later by calling a function on the client itself, instead of returning a reply.
neg[h](`g;3;`f) sends the request asynchronously — the client doesn't wait for a result. Inside g, .z.w is the handle pointing back at the caller, so neg[.z.w](callbackFunction;data+1) sends the result to that same client as a new async message. The client receives it as an ordinary incoming request and runs f[4].
Sending the request asynchronously is what lets the client carry on with other work instead of waiting. (If the client sent h(g;3;f) synchronously instead, it would still work: while a client waits for a synchronous reply, it continues to process async messages arriving on that connection, so f runs, and then the sync call returns g's own result. But the client would be blocked for the duration.)