Warm tip: This article is reproduced from serverfault.com, please click

Create a lock/unlock mechanism in async mode for Python

发布于 2020-12-02 07:00:51

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?

Questioner
datdinhquoc
Viewed
0
4,160 2020-12-02 17:16:37

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)