I have this new_lock function in JS, it's useful to avoid callback hell:
function new_lock(){
var unlock,lock = new Promise((res,rej)=>{ unlock=res; });
return [lock,unlock];
}
var [lock,unlock] = new_lock();
call_some_func_with_callback(data,function(){
print(1);
print(2);
unlock();
});
await lock;
print(3)
And this is my async Python main function to use 'await' keyword inside:
import asyncio as aio
def new_lock():
?How to put code here?
return lock,unlock
async main():
lock,unlock = new_lock()
def cb(ackdata):
print(1)
print(2)
unlock()
# Python web server emits to client side (browser)
socketio.emit("eventname",data,callback=cb)
await lock
print(3)
if __name__=="__main__":
loop = aio.get_event_loop()
t = loop.create_task(main())
loop.run_until_complete(t)
How to create the Python equivalent of the 'new_lock' function in JS? Or even that new_lock function necessary in Python?
Why not just use socket.io's AsyncClient
or AsyncServer
class and just await sio.emit()
?
Failing that, you're looking for an Event
async primitive:
import asyncio as aio
async main():
ev = aio.Event()
def cb(ackdata):
print(1)
print(2)
ev.set()
await socketio.emit("eventname",data,callback=cb)
await ev.wait()
print(3)
my client side is not python, it's javascript in browser and the js lib is from socket.io
I understand, but your question is about async Python code that uses the Socket.io library, and you're attempting to do what Socket.io does already with the async client.
tks, that aio.Event() is simple enough, lock=ev.wait(), and unlock=ev.set
Will
asyncio.Event
work in the OP's code? The socketio client examples usually end withsio.wait()
which looks like it has its own event loop.i added 'await' before socketio.emit and it worked